gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:12:28 25 4
gpt4 key购买 nike

以下函数试图找到单向链表的 nthlast 元素。

例如:

如果元素是 8->10->5->7->2->1->5->4->10->10 那么结果是7th 到最后一个节点是 7

任何人都可以帮助我了解这段代码是如何工作的,或者是否有更好更简单的方法?

LinkedListNode nthToLast(LinkedListNode head, int n) {
if (head == null || n < 1) {
return null;
}

LinkedListNode p1 = head;
LinkedListNode p2 = head;

for (int j = 0; j < n - 1; ++j) { // skip n-1 steps ahead
if (p2 == null) {
return null; // not found since list size < n
}
p2 = p2.next;
}

while (p2.next != null) {
p1 = p1.next;
p2 = p2.next;
}

return p1;
}

最佳答案

这个算法的关键是设置两个指针 p1p2 最初相隔 n-1 个节点所以我们想要 p2 指向列表开头的 (n-1)th 节点然后我们移动 p2 直到它到达 last 列表的节点。一旦 p2 到达列表的末尾,p1 将指向列表末尾的第 n 个节点。

我已将解释内嵌为注释。希望对您有所帮助:

// Function to return the nth node from the end of a linked list.
// Takes the head pointer to the list and n as input
// Returns the nth node from the end if one exists else returns NULL.
LinkedListNode nthToLast(LinkedListNode head, int n) {
// If list does not exist or if there are no elements in the list,return NULL
if (head == null || n < 1) {
return null;
}

// make pointers p1 and p2 point to the start of the list.
LinkedListNode p1 = head;
LinkedListNode p2 = head;

// The key to this algorithm is to set p1 and p2 apart by n-1 nodes initially
// so we want p2 to point to the (n-1)th node from the start of the list
// then we move p2 till it reaches the last node of the list.
// Once p2 reaches end of the list p1 will be pointing to the nth node
// from the end of the list.

// loop to move p2.
for (int j = 0; j < n - 1; ++j) {
// while moving p2 check if it becomes NULL, that is if it reaches the end
// of the list. That would mean the list has less than n nodes, so its not
// possible to find nth from last, so return NULL.
if (p2 == null) {
return null;
}
// move p2 forward.
p2 = p2.next;
}

// at this point p2 is (n-1) nodes ahead of p1. Now keep moving both forward
// till p2 reaches the last node in the list.
while (p2.next != null) {
p1 = p1.next;
p2 = p2.next;
}

// at this point p2 has reached the last node in the list and p1 will be
// pointing to the nth node from the last..so return it.
return p1;
}

或者,我们可以将 p1p2 设置为 n 个节点而不是 (n-1),然后移动 p2 直到列表的末尾而不是移动到最后一个节点:

LinkedListNode p1 = head;
LinkedListNode p2 = head;
for (int j = 0; j < n ; ++j) { // make then n nodes apart.
if (p2 == null) {
return null;
}
p2 = p2.next;
}
while (p2 != null) { // move till p2 goes past the end of the list.
p1 = p1.next;
p2 = p2.next;
}
return p1;

关于algorithm - 如何从单向链表的末尾找到第 n 个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2598348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com