leetcode-剑指 Offer 24. 反转链表

双指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public ListNode reverseList(ListNode head) {
if(head.next == null){
return head;
}

ListNode cur = head;
ListNode pre = null;
while(cur != null){
cur.next = pre;
pre = cur;
}
}
}

递归

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