funcmergeKLists1(lists []*ListNode) *ListNode { pre := &ListNode{} cur := &ListNode{} iflen(lists) == 0 { returnnil } pre = lists[0] for i := 1; i < len(lists); i++ { cur = lists[i] pre = mergeTwoLists(pre, cur) // 21题函数 } return pre }
// 使用最小堆存储所有链表头结点节点 // 遍历最小堆,取出最小节点添加到新链表,同时将取出节点下一个节点放入最小堆中 funcmergeKLists(lists []*ListNode) *ListNode { h := new(minHeap) // 将所有链表的头结点放入最小堆 for _, list := range lists { if list != nil { heap.Push(h, list) } }
head := &ListNode{} pre := head for h.Len() > 0 { // 取出最小节点 node := heap.Pop(h).(*ListNode) if node.Next != nil { // 将最小节点下一节点加入最小堆 heap.Push(h, node.Next) } // 最小节点放入链表 pre.Next = node pre = pre.Next } return head.Next }
funcgetIntersectionNode(headA, headB *ListNode) *ListNode { var lenA, lenB int for p := headA; p != nil; p = p.Next { lenA++ } for p := headB; p != nil; p = p.Next { lenB++ } p1, p2 := headA, headB if lenA > lenB { for i := 0; i < lenA-lenB; i++ { p1 = p1.Next } } else { for i := 0; i < lenB-lenA; i++ { p2 = p2.Next } }
funchasCycle(head *ListNode)bool { slow, fast := head, head for fast != nil && fast.Next != nil { slow = slow.Next fast = fast.Next.Next if slow == fast { returntrue } } returnfalse }
funcdetectCycle(head *ListNode) *ListNode { slow, fast := head, head for fast != nil && fast.Next != nil { slow = slow.Next fast = fast.Next.Next if slow == fast { p := head for p != slow { p = p.Next slow = slow.Next } return p } } returnnil }
funcdeleteDuplicates(head *ListNode) *ListNode { if head == nil { returnnil } slow, fast := head, head for fast != nil { if slow.Val != fast.Val { // nums[slow] = nums[fast] slow.Next = fast // slow ++ slow = slow.Next } // fast ++ fast = fast.Next } // 断开与后面重复元素的链接 slow.Next = nil return head }