反转链表

反转链表

递归方法

1
2
3
4
5
6
7
8
   public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
}

循环方法

1
2
3
4
5
6
7
8
9
10
public ListNode reverseList(ListNode head) {
ListNode cur = head, pre = null, next = null;
while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}