LeetCode 連結串列解題彙總 Java版

magicTan發表於2019-04-21

160. Intersection of Two Linked Lists (Easy)

  • 找出兩個單連結串列的交點
  • 160. Intersection of Two Linked Lists
  • 要求:
    1. 沒有交點時返回null;
    2. 不能改錶連結串列結構;
    3. 可以假設連結串列不成環;
    4. 時間複雜度O(n),空間複雜度O(1)。
A:          a1 → a2
                    ↘
                      c1 → c2 → c3
                    ↗
B:    b1 → b2 → b3
複製程式碼
  • 思路:
    • 連結串列A的長度為a+c,連結串列B的長度為b+c,c為公共部分長度,所以有a+c+b=b+c+a,即指標先走完A連結串列然後繼續從B連結串列頭開始走,B指標走完B連結串列然後從A連結串列頭開始走,如果兩個連結串列相交,那麼A、B兩個指標就會在共同連結串列相遇
  • 程式碼:
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    //任何一個連結串列為空都可以返回null
    if (headA == null || headB == null) {
        return null;
    }
    //記住A指標到達連結串列尾部的次數
    //當次數為2時,表示已到了連結串列B的尾部,此時還未相交就可以返回null
    int count = 0;
    ListNode l1 = headA, l2 = headB;
    while (l1 != l2) {
        if (l1 == null) {
            count++; //到達連結串列末尾則計數器加1
            if (count == 2) { //兩次到達連結串列末尾都沒相交,返回null
                return null;
            }
            l1 = headB;
        } else {
            l1 = l1.next;
        }
        l2 = l2 == null ? headA : l2.next;
    }
    return l1;
}
複製程式碼

206. Reverse Linked List (Easy)

//普通迴圈
public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }
    ListNode temp;
    ListNode newHead = null;
    while (head.next != null) {
        temp = head.next;
        head.next = newHead;
        newHead = head;
        head = temp;
    }
    head.next = newHead;
    return head;
}

//普通迴圈-使用哨兵簡化程式碼
public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }
    ListNode temp;
    ListNode newHead = new ListNode(0);
    while (head != null) {
        temp = head.next;
        head.next = newHead.next;
        newHead.next = head;
        head = temp;
    }
    return newHead.next;
}

//遞迴
public static ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }
    ListNode next = head.next;
    ListNode newHead = reverseList(next);
    head.next = null;
    next.next = head;
    return newHead;
}
複製程式碼

21. Merge Two Sorted Lists (Easy)

class Solution {

    public  ListNode head;
    public  ListNode tail;

    public  ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        head = tail = null;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                add(l1);
                l1 = l1.next;
            } else {
                add(l2);
                l2 =  l2.next;
            }
        }
        if (l1 != null) {
            add(l1);
        } else if (l2 != null) {
            add(l2);
        }
        return head;
    }

    public  void add(ListNode next) {
        if (head == null) {
            head = tail = next;
        } else {
            tail.next = next;
            tail = next;
        }
    }
}
複製程式碼

相關文章