反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reverse-linked-list
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
class Solution {
public ListNode reverseList(ListNode head) {
// return reverseLinkedListII(head);
// return reverseLinkedListI(head);
return reverseLinkedListIII(head, null);
}
//方法三:遞歸
private ListNode reverseLinkedListIII(ListNode head, ListNode newHead) {
if (head == null) return newHead;
ListNode next = head.next;
head.next = newHead;
return reverseLinkedListIII(next, head);
}
//方法二:遞歸
private ListNode reverseLinkedListII(ListNode head) {
//遞歸終止條件
if (head == null || head.next == null) return head;
////這裏的curr就是最後一個節點
ListNode curr = reverseList(head.next);
head.next.next = head;
//防止鏈表循環,需要將head.next設置爲空
head.next = null;
////每層遞歸函數都返回cur,也就是最後一個節點
return curr;
}
//方法一:雙指針迭代
//定義兩個指針curr和prev
//遍歷curr,將curr的next指向prev,同時curr和prev同時前進一位
//返回prev爲頭結點
private ListNode reverseLinkedListI(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}