Leetcode206-反转链表

LeetCode206-反转链表

维护三个指针

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

递归实现

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