且构网

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

如何从单向链表的末尾找到第n个元素?

更新时间:2023-02-13 23:38:27

您的算法首先创建对链表中相距 N 个节点的两个节点的引用.因此,在您的示例中,如果 N 为 7,那么它会将 p1 设置为 8,将 p2 设置为 4.

Your algorithm works by first creating references to two nodes in your linked list that are N nodes apart. Thus, in your example, if N is 7, then it will set p1 to 8 and p2 to 4.

然后它将每个节点的引用推进到列表中的下一个节点,直到 p2 到达列表中的最后一个元素.同样,在您的示例中,这将是 p1 为 5 且 p2 为 10 时.此时,p1 指的是第 N 个到列表中的最后一个元素(根据它们相隔 N 个节点的属性).

It will then advance each node reference to the next node in the list until p2 reaches the last element in the list. Again, in your example, this will be when p1 is 5 and p2 is 10. At this point, p1 is referring to the Nth to the last element in the list (by the property that they are N nodes apart).