LeetCode 鏈表解題彙總 Java版

19. Remove Nth Node From End of List (Medium)

  • 移除倒數第N個節點
  • 19. Remove Nth Node From End of List
  • 代碼:
    • 先判斷通過n個節點後是否恰好到了末尾,是的話鏈表長度爲n,第n個節點就是頭結點,直接返回head.next的鏈表。
    • 通過n個節點後,還未到末尾,此時開啓雙指針,slow和fast同時日後走,fast和slow之間差距爲n,fast到末尾,slow就是距離末尾n的節點,移除掉,返回head
public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode fast = head;
    while (n-- > 0) {
        fast = fast.next;
    }
    if (fast == null) {
        return head.next;
    }
    ListNode slow = head;
    while (fast.next != null) {
        fast = fast.next;
        slow = slow.next;
    }
    slow.next = slow.next.next;
    return head;
}
複製代碼

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;
        }
    }
}
複製代碼

23. Merge k Sorted Lists (Hard)

  • 合併k個有序鏈表
  • 23. Merge k Sorted Lists
  • 代碼:分治算法將鏈表兩兩合併,最後合併成一個鏈表,平均一條鏈表n個節點,合併兩條鏈表爲O(n),k條鏈表合併爲O(logk),合併爲O(nlogk)
class Solution {
   public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null || lists.length == 0) return null;
        return partion(lists, 0, lists.length - 1);
    }

    private ListNode partion(ListNode[] lists, int start, int end) {
        if(start == end) {
            return lists[start];
        }
        else if(start < end) {
            int mid = (start + end) / 2;
            ListNode l1 = partion(lists, start, mid);
            ListNode l2 = partion(lists, mid + 1, end);
            return merge(l1, l2);
        }
        else {
            //not gonna happen.
            return null;
        } 
    }

    private ListNode merge(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        if(l1.val < l2.val) {
            l1.next = merge(l1.next, l2);
            return l1;
        } else {
            l2.next = merge(l1, l2.next);
            return l2;
        }
    }
}
複製代碼

24. Swap Nodes in Pairs (Medium)

  • 交換鏈表相鄰兩個節點,只能修改引用,不容許修改節點的值
  • 24. Swap Nodes in Pairs
  • 代碼:
//新增一個哨兵頭結點,經過哨兵節點簡化代碼
    public ListNode swapPairs(ListNode head) {
        ListNode result = new ListNode(0);
        result.next = head;
        ListNode last = result;
        ListNode temp;
        //當前節點後存在2個節點能夠交換
        while (last.next != null && last.next.next != null) {
            temp = last.next.next;
            last.next.next = temp.next;
            temp.next = last.next;
            last.next = temp;
            last = last.next.next;
        }
        return result.next;
    }
複製代碼

61. Rotate List (Medium)

  • 給定一個鏈表,和一個非負數k,旋轉鏈表k次,k是非負數
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
複製代碼
  • 61. Rotate List
  • 代碼:
    • 使用雙指針法,fast循環向右移動k位,遇到結尾就從head從新開始,結束fast就是結果鏈表的頭結點。此時slow指向head,fast和slow同時向右移動,直到fast.next爲空,將fast.next指向head,slow.next置爲空,便可得結果鏈表
    • 注意邊界狀況以及k對鏈表長度取餘的優化
public ListNode rotateRight(ListNode head, int k) {
        if (head == null || k == 0 || head.next == null) {
            return head;
        }
        ListNode fast = head;
        for (int i = 0, count = 0; i < k; i++) {
            if (fast.next != null) {
                fast = fast.next;
                count++;
            } else {
                k = k % (count+1);
                i = -1;
                fast = head;
            }
        }
        if (fast == head) {
            return head;
        }
        ListNode slow = head;
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        ListNode result = slow.next;
        fast.next = head;
        slow.next = null;
        return result;
    }
複製代碼

82. Remove Duplicates from Sorted List II (Medium)

  • 給定一個已排序的鏈表,刪除全部重複的節=-。
Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2
Example 2:

Input: 1->1->2->3->3
Output: 1->2->3
複製代碼
public static ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode sentinel = new ListNode(-1);
        sentinel.next = head;
        ListNode nodeA = sentinel;
        ListNode nodeB = nodeA.next.next;
        while (nodeB != null) {
            if (nodeA.next.val == nodeB.val) {
                while (nodeB != null && nodeA.next.val == nodeB.val) {
                    nodeB = nodeB.next;
                }
                nodeA.next = nodeB;
                if (nodeB != null) {
                    nodeB = nodeB.next;
                }
            } else {
                nodeA = nodeA.next;
                nodeB = nodeB.next;
            }
        }
        return sentinel.next;
    }
複製代碼

83. Remove Duplicates from Sorted List (Easy)

  • 給定一個已排序的鏈表,刪除多餘的節點,使每一個元素只出現一次
Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2
Example 2:

Input: 1->1->2->3->3
Output: 1->2->3
複製代碼
public static ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode nodeA = head;
        ListNode nodeB = head.next;
        while (nodeB != null) {
            if (nodeA.val == nodeB.val) {
                nodeB = nodeA.next = nodeB.next;
            } else {
                nodeA = nodeB;
                nodeB = nodeB.next;
            }
        }
        return head;
    }
複製代碼

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;
}
複製代碼

24. Remove Nth Node From End of List (Medium)

  • 移除倒數第N個節點
  • 代碼:
    • 先判斷通過n個節點後是否恰好到了末尾,是的話鏈表長度爲n,第n個節點就是頭結點,直接返回head.next的鏈表。
    • 通過n個節點後,還未到末尾,此時開啓雙指針,slow和fast同時日後走,fast和slow之間差距爲n,fast到末尾,slow就是距離末尾n的節點,移除掉,返回head
public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode fast = head;
    while (n-- > 0) {
        fast = fast.next;
    }
    if (fast == null) {
        return head.next;
    }
    ListNode slow = head;
    while (fast.next != null) {
        fast = fast.next;
        slow = slow.next;
    }
    slow.next = slow.next.next;
    return head;
}
複製代碼
相關文章
相關標籤/搜索