gpt4 book ai didi

java - 如何反转链表 - 详细说明

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

谁能分享解释如何反转链表的代码的链接?或者有人能解释下面的代码片段吗?

我试过画/写它,但仍然不明白节点是如何反转的。

public void reverseList() {
Node reversedPart = null;
Node current = head;
while (current != null) {
Node next = current.next;
current.next = reversedPart;
reversedPart = current;
current = next;
}
head = reversedPart;
}

最佳答案

让我们来看一个简单的例子:

1 > 2 > 3 > 4 > 5 > null - our list

Before the while loop: node = 1, head = null

While moving over the list:

1: 1 > null; node = 1, head = null, node.next = head, head = node

2: 2 > 1 > null; node = 2, head = 1, node.next = head, head = node

3: 3 > 2 > 1 > null; node = 3, head = 2, node.next = head, head = node

4: 4 > 3 > 2 > 1 > null; node = 4, head = 3, node.next = head, head = node

5: 5 > 4 > 3 > 2 > 1 > null; node = 5, head = 4, node.next = head, head = node

注释代表算法的第一步:

public Node reverseList(Node head) {
Node focusNode = head; // focusNode = 1
head = null;
while (focusNode != null) {
Node parent = focusNode; // parent = 1
focusNode = focusNode.next; // focusNode = 2; moving over the list...
parent.next = head; // parent.next = null (1 -> null)
head = parent; // head = 1
}
return head;
}

关于java - 如何反转链表 - 详细说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31765171/

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