如何反向链接列表-详细说明 [英] How to reverse a linked list - detailed explanation
本文介绍了如何反向链接列表-详细说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何人都可以共享指向解释如何反转linked list?
的代码的链接吗?还是有人可以解释下面的代码片段?
Can anyone share a link to the code which explains of how to reverse a linked list?
Or could somebody explain the code snippet below?
我尝试绘制/编写它,但是仍然不了解节点如何反转.
I've tried to draw/write it, but still don't get how nodes get reversed.
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;
}
推荐答案
让我们看一个简单的示例:
Let's take a look into a simple example:
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
注释代表算法的第一步:
Comments represent the first step of the algorithm:
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;
}
这篇关于如何反向链接列表-详细说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文