Leetcode 206. Reverse Linked List

GoodJobJasper發表於2020-12-25

在這裡插入圖片描述
方法1: 這道easy題兩個方法我都沒有解出來,主要原因是感覺還是接觸連結串列題目太少。第一個方法是iterate。這個方法關鍵在於要新建一個prev node,初始化為null。具體思路是curr node的next指向prev node,然後在向右移動curr node和pre node。時間複雜度n,空間複雜度1

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while(curr != null){
            ListNode temp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = temp;
        }
        return prev;
    }
}

方法2: recursion。其實連結串列題的recursion邏輯並不是很難想,主要是正確的寫出這個邏輯,這中間會比較繞。時間複雜度n,空間複雜度n。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head ==null || head.next == null) return head;
        ListNode p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
}

總結:

  • 這是一道非常經典的題目,雖然是easy題,但是學到了不少連結串列swap之類的操作

相關文章