如何打印链表的斐波那契节点?例如,我们在链接列表中打印第一,第二,第三,第五,第八等节点。

问题描述 投票:2回答:2
我正在尝试找出最有效的方法。我下面的代码用于打印斐波那契数列的前十个元素(使用备注)

int main() { int arrayWithFibIndices[100] = {0}; //Explanation for this array comes later int series[10] = {0}; //array to store the fibonacci values for last two iterations series[0] = 1; //hard coding the first two elements of the fib series series[1] = 2; for (int i = 0; i < 10; i++) { if (series[i] != 0) { printf ("series[%d]=%d.\n", i, series[i]); } else { series[i] = series[i - 1] + series[i - 2]; printf ("series[%d]=%d.\n", i, series[i]); } arrayWithFibIndices[series[i]] = 1; } }

我还具有以下逻辑来迭代地打印链接列表。

void printLL(struct node *temp) { int i = 0; while(temp != NULL) { if (arrayWithFibIndices[i] != 0) //reason explained later below { printf("data:%d ", temp->data); temp = temp->next; } i++; } printf("\n"); }

我正在尝试找出最有效的方法是什么?我想到的第一件事是创建一个新的数组arrayWithFibIndices []并将该数组的所有元素初始化为0。每当遇到斐波那契值时,我们便将arrayWithFibIndices []中的索引填充为1。稍后我们可以在打印链接列表的值之前,请检查arrayWithFibIndices []的每个索引。

我想到的第二个想法是创建一个队列。我将排队所有Fibonacci元素,当要打印“链接列表”时,我将在成功匹配时出队(匹配是队列元素与链接列表的第i个元素匹配。)>

你们还有其他建议吗?

我正在尝试找出最有效的方法。我下面有以下代码用于打印斐波那契数列的前十个元素(使用记忆)int main(){int ...

c structure
2个回答
0
投票
您在描述中建议的解决方案将起作用。但是,您无需通过即可获得所有斐波那契数字的列表。您可以只跟踪先前的编号,并使用它来偏移列表中的当前节点。

这里是一个简单的示例,说明其如何工作。


0
投票
如果您也在设计和构建列表,则在构建过程中,可以将斐波那契节点的地址复制到struct node*的单独数组中。为了管理节点的任何重新排序,您可以将列表位置存储在每个节点中(并在例如添加或删除节点时更改列表位置)。如果列表会经常被处理,这会产生开销,但是打印斐波那契节点非常有效:只需遍历指针数组,而无需遍历链接列表。
© www.soinside.com 2019 - 2024. All rights reserved.