How to reverse a linked list - detailed explanation

旧巷老猫 提交于 2019-12-12 18:34:57

问题


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;
}

回答1:


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;
}



回答2:


Firstly, usage of Node next should be avoided inside the while loop to remove any kind of confusion. You should better rename next to nodeNext, and also declare Node nodeNext outside the while loop, and just use nodeNext = current.next; for sorting out any confusion. I think that's your source of confusion.

What this code is doing that it is reversing the direction of links for each node.

Each node's next node direction is being reversed. The direction of pointing of first node towards second node(node ahead to first node originally) is reversed, the first node points to its predecessor, and the node ahead to it points to the first node.

This keeps on repeating till the last node, i.e., current!=null. After that, as soon as the current becomes null, the loop doesn't iterate any further and all the elements have been reversed.



来源:https://stackoverflow.com/questions/31765171/how-to-reverse-a-linked-list-detailed-explanation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!