剑指offer 24. 反转链表
题目描述
解题思路
递归
注意,这种链表翻转题,一定要自己举个例子把链表画出来,然后模拟翻转的过程。
class Solution {
//翻转从head开始的链表,并返回翻转后的头结点
public ListNode reverseList(ListNode head) {
//base case
if (head == null || head.next == null) return head;
//新链表的头结点
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
迭代
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return null;
ListNode prev = null, curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}