单链表的初始状态:
进行一次迭代后的状态为:
可以看出迭代体代码为:
Node prev = null;
Node next;
//迭代体代码
next = head.next; //保存next节点
head.next = prev; //将head.next节点指向prev
prev = head; //将prev节点指向head
head = next; //将head节点指向next
import java.util.SortedMap;
/**
* Created by chaoyang805 on 2015/12/3.
*/
public class Node {
public static void main(String[] args) {
Node head = new Node(0);
Node tail = head;
for (int i = 1; i < 10; i++) {
Node p = new Node(i);
tail.next = p;
tail = p;
}
head = reverse(head);
while (head.next != null) {
System.out.println(head.data);
head = head.next;
}
}
public Node(int data) {
this.data = data;
}
int data;
public Node next = null;
public static Node reverse(Node head) {
Node prev = null;
Node next;
while (head != null) {
next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}