public class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
public Node reverse(Node head) {
Node pre = null;
Node next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
How does this code flip in the while loop? I want to be more detailed. I debugged it several times and still don’t understand what’s going on.
大家讲道理2017-06-23 09:15:13
It will be easier to understand the purpose if you refer to it. The most confusing part is to deal with it from right to left, because you have to save the things at the back first, otherwise they will be overwritten and lost.
pre head
+----+ +----+ +> +----+
| | | | | | |
| | | | | | |
| | | | | | |
+----+ +----+ | +----+
| | | | | | |
| | | | | | |
+----+ +-+--+ | +----+
| |
+-----+
pre head next next = head.next;
+----+ +----+ +> +----+
| | | | | | |
| | | | | | |
| | | | | | |
+----+ +----+ | +----+
| | | | | | |
| | | | | | |
+----+ +-+--+ | +----+
| |
+-----+
pre head next
+----+ <+ +----+ +----+
| | | | | | |
| | | | | | |
| | | | | | |
+----+ | +----+ +----+
| | | | | | |
| | | | | | |
+----+ | +-+--+ +----+
| | head.next = pre;
+----+
next
pre head pre = head;
+----+ <+ +----+ +----+ head = next;
| | | | | | |
| | | | | | |
| | | | | | |
+----+ | +----+ +----+
| | | | | | |
| | | | | | |
+----+ | +-+--+ +----+
| |
+----+