且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从结束寻找“第N个节点”的链表

更新时间:2023-02-14 08:07:58

访问节点两次如下:

创建一个大小为n的空数组,从索引0开始指向此数组的指针,并从链表的开头开始迭代。每次你访问一个节点存储它在数组的当前索引,并提前数组指针。当您填充数组时,回绕并覆盖之前存储的元素。当到达列表的末尾时,指针将从列表末尾指向元素n。

Create an empty array of size n, a pointer into this array starting at index 0, and start iterating from the beginning of the linked list. Every time you visit a node store it in the current index of the array and advance the array pointer. When you fill the array, wrap around and overwrite the elements you stored before. When you reach the end of the list, the pointer will be pointing at the element n from the end of the list.

但这也只是一个O(n)算法。你现在做的是好的。我没有看到任何令人信服的理由改变它。

But this also is just an O(n) algorithm. What you are currently doing is fine. I see no compelling reason to change it.