在链表遍历的过程中将指针顺序置换,代码如下
public static Node<String> reverse(Node<String> head) {
Node<String> pre = null;
Node<String> next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
/*
第一次遍历
A -> B -> C -> D -> E -> F
^ ^
| |
head next
next = head.next; // next 指向 B
head.next = pre; // head.next = null,此时 head = A
pre = head; // pre = A
head = next; // head 指向B
遍历后
B -> C -> D -> E -> F A
^ ^
| |
head pre
第二次遍历
B -> C -> D -> E -> F
^ ^
| |
head next
next = head.next; // next 指向 C
head.next = pre; // head.next = A,此时 head = B -> A
pre = head; // pre = B -> A
head = next; // head 指向 C
遍历后
C -> D -> E -> F B -> A
^ ^
| |
head pre
………………
*/
}