public class Node{
int value;
Node next;
public Node(int value){
this.value = value;
}
//这个反转单链表这样想象,把原先链表的节点从头取出来接在另一个新链表上
public Node reverse(Node head){
if(root == null){
return null;
}
Node pre = null;//pre可以认为是不断构造的反转链表的头结点
Node next = null;//next用来保存next的值
while(head != null){//这里直接修改head,这个head用不着保存了
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
The time complexity is O (n), just look at singly-linked list traversal.