两种方法倒置一个链表
1. 递归
亮点在于构建一个假的head:newHead,代码如下:
class RecursivelyReverseLinkedList{
ListNode newHead = new ListNode(0);
public ListNode reverseList(ListNode head) {
if(head == null) {
return null;
} // empty list
reverseList(newHead, head); // recursion
return newHead.next;
}
public ListNode reverseList(ListNode head, ListNode p) {
head.next = p; // connect the head and the list
if(p.next != null) {
ListNode p1 = new ListNode(0); // new head
ListNode q = reverseList(p1, p.next); // get the last non empty node
p.next = null; // to put the p in new list
q.next = p; // connect
head.next = p1.next; // connect
}
return p; // return the last non empty node
}
}
2. 迭代
public ListNode reverseList(ListNode head) {
if(head == null) {
return null;
} // return empty list
ListNode newHead = new ListNode(0); // new head
ListNode p = head; // temp index
while(p != null) {
ListNode temp = p; // get off the first node
p = p.next; // move to next node
temp.next = newHead.next; // connect
newHead.next = temp;
}
return newHead.next; // return the right head
}