给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
public ListNode reverse(ListNode head) {
if(head == null){
return null;
}
//用来保存上一个tmp
ListNode prev = null;
while (head != null) {
ListNode tmp = head;
head = head.next;
tmp.next = prev;
prev = tmp;
}
return prev;
}
缺陷:没有在原链表的基础上进行反转
public ListNode ReverseList(ListNode head) {
if(head == null){
return null;
}
ListNode rHead = null;
ListNode prior = null;//store prior
ListNode q = head;//store current
while(q != null){
ListNode next = q.next;//store the next
if(next == null){
rHead = q;
}
q.next = prior;
prior = q;
q = next;
}
return rHead;
}