是否有人可以共享一个指向代码的链接来解释如何反转alinked list?或者有人可以解释下面的代码片段?
我试过画/写它,但仍然不知道节点是如何反转的。

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/

10-10 10:16