鏈表相關算法整理【實時更新】

1. 鏈表刪除重複節點

  • 重複節點不保留:雙重循環
class Solution:
    def deleteDuplication(self, p):
        # write code here
        root = ListNode(0)
        root.next = p
        pre = root
        while p:
            if p.next and p.val == p.next.val:
                while p.next and p.val == p.next.val:
                    p.next = p.next.next
                p = p.next
                pre.next = p 
            else:
                pre = p
                p = p.next
  • 重複節點保留:單循環
# 待補充

2. 鏈表倒數第k個節點

  • 快慢指針
class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        slow = head
        fast = head
        for _ in range(k):
            if not fast:
                return None
            fast = fast.next
        while fast:
            slow = slow.next
            fast = fast.next
        return slow

3. 反轉鏈表

  • 三指針
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        head = pHead
        if head == None or head.next == None:
            return head
        pre = None
        while head:
            nex = head.next # 記錄當前節點的下一節點
            head.next = pre # 當前節點指向取反
            pre = head      # nex向前走一步
            head = nex      # head向前走一步
        return pre

4. 合併排序鏈表

class Solution:
    # 返回合併後列表
    def Merge(self, p1, p2):
        # write code here
        cur = head = ListNode(0) # 建立helper指針
        while p1 and p2:
            if p1.val<=p2.val:
                cur.next = p1
                p1 = p1.next
            else:
                cur.next = p2
                p2 = p2.next
            cur = cur.next
        if p1 == None:
            cur.next = p2
        elif p2 == None:
            cur.next = p1
        else:
            cur.next = None
        return head.next

5. 兩鏈表的第一個公共節點

class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if (pHead1 == NULL || pHead2 == NULL){
            return NULL;
        }
        ListNode* p1 = pHead1;
        ListNode* p2 = pHead2;
        while(p1 != p2){
            p1 = p1->next;
            p2 = p2->next;
            if(p1 != p2){
                if(p1 == NULL) p1 = pHead2;
                if(p2 == NULL) p2 = pHead1;
            }
        }
        return p1; 
    }
};

6. 鏈表中環的入口

  • 快慢指針相遇確定有環
  • slow2從head開始移動,slow從相遇點開始移動,交點就是環的入口
class Solution:
    def EntryNodeOfLoop(self, phead):
        # write code here
        if not phead:
            return None
        slow = phead
        fast = phead
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                slow2 = phead
                while slow !=slow2:
                    slow = slow.next
                    slow2 = slow2.next
                return slow
        return None
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章