迭代
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
递归(使用额外参数)
和上面迭代的思想一样。
class Solution {
public ListNode reverseList(ListNode head) {
return reverse(head, null);
}
ListNode reverse(ListNode cur, ListNode pre){
if(cur == null) return pre;
ListNode res = reverse(cur.next, cur);
cur.next = pre;
return res;
}
}
递归(不使用额外参数)
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}
}