【Leetcode】链表——全题解

2020-08-07  本文已影响0人  李白开水

当前Leetcode的链表标签题目一共53道题,除了会员题目,题解基本都在这了,还可能陆续更新一题多解~

简单

(1)删除节点

面试题 02.03. 删除中间节点

237. 删除链表中的节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        if node.next:
            if node.next.next:
                node.val = node.next.val
                node.next = node.next.next
            else:
                node.val = node.next.val
                node.next = None
        # 这一行有没有都可以通过,因为当前节点不为最后一个节点,而且不要求返回
        return None
-------------------------------------------------------------------------------------------------
        # 也可以:
        if node.next:
            node.val = node.next.val
            if node.next.next:
                node.next = node.next.next
            else:
                node.next = None

面试题 02.01. 移除重复节点

83. 删除排序链表中的重复元素

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeDuplicateNodes(self, head: ListNode) -> ListNode:
        mydict = {}
        newhead = ListNode(0)
        n = newhead
        h = head

        while h:
            if h.val not in mydict:
                mydict[h.val] = True
                n.next = ListNode(h.val)
                n = n.next
            h = h.next
            
        return newhead.next

原地:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeDuplicateNodes(self, head: ListNode) -> ListNode:
        mydict = {}
        newhead = ListNode(0)
        newhead.next = head
        cur = newhead
        nex = cur.next
        
        while nex:
            if nex.val not in mydict:
                cur.next = nex
                mydict[nex.val] = True
                cur = cur.next
            nex = nex.next
        cur.next = None
        return newhead.next

203. 移除链表元素

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        newhead = ListNode(0)
        newhead.next = head
        cur = newhead
        nex = cur.next

        while nex:
            if nex.val != val:
                cur.next = nex
                cur = cur.next
            nex = nex.next
        cur.next = None
        return newhead.next

剑指 Offer 18. 删除链表的节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteNode(self, head: ListNode, val: int) -> ListNode:
        newhead = ListNode(0)
        newhead.next = head
        cur, nex = newhead, newhead.next
        while nex:
            if nex.val != val:
                cur.next = nex
                cur = cur.next
            nex = nex.next
        cur.next = None
        return newhead.next

(2)反转链表

206. 反转链表

剑指 Offer 24. 反转链表

image.png

把第一个节点指向newhead


image.png

newhead指向cur


image.png
cur指向nex
image.png
nex指向它的下一个
image.png
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head:
            return None
        newhead = None
        cur = head
        nex = cur.next
        while cur:
            cur.next = newhead
            newhead = cur
            cur = nex
            if nex:
                nex = nex.next
        return newhead

(3)双指针:中间节点、环形链表

876. 链表的中间结点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        fast = head
        slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        return slow

剑指 Offer 22. 链表中倒数第k个节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
        if not head:
            return None
        fast = head
        slow = head
        while k > 0:
            fast = fast.next
            k -= 1
        while fast:
            fast = fast.next
            slow = slow.next
        return slow

面试题 02.02. 返回倒数第 k 个节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def kthToLast(self, head: ListNode, k: int) -> int:
        if not head:
            return None
        fast, slow = head, head
        while k > 0:
            fast = fast.next
            k -= 1
        while fast:
            fast = fast.next
            slow = slow.next
        return slow.val

环形链表:

141. 环形链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

两个链表

21. 合并两个有序链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if not l1 or not l2:
            return l2 or l1
        tmp1, tmp2 = l1, l2
        newhead = ListNode(0)
        cur = newhead
        while tmp1 and tmp2:
            if tmp1.val > tmp2.val:
                cur.next = tmp2
                tmp2 = tmp2.next
            else:
                cur.next = tmp1
                tmp1 = tmp1.next
            cur = cur.next
        if tmp1:
            cur.next = tmp1
        else:
            cur.next = tmp2
        return newhead.next

(4)反转链表和双指针

234. 回文链表

面试题 02.06. 回文链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        if not head:
            return True
        
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        
        newhead = None
        cur = slow
        nex = cur.next
        while cur:
            cur.next = newhead
            newhead = cur
            cur = nex
            if nex:
                nex = nex.next
        
        h = head
        while h and newhead:
            if h.val == newhead.val:
                h = h.next
                newhead = newhead.next
            else:
                return False
        return True

(5)双指针解决两个链表相交问题

160. 相交链表

剑指 Offer 52. 两个链表的第一个公共节点

面试题 02.07. 链表相交

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if not headA or not headB:
            return None
        tmpA, tmpB = headA, headB
        while tmpA != tmpB:
            if tmpA:
                tmpA = tmpA.next
            else:
                tmpA = headB
            if tmpB:
                tmpB = tmpB.next
            else:
                tmpB = headA
        return tmpA

(6)其他

剑指 Offer 06. 从尾到头打印链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
        res = []
        h = head
        while h:
            res.append(h.val)
            h = h.next
        return res[::-1]

1290. 二进制链表转整数

举例:
如果输入是[1,0,0,1,0],它的十进制树应该是18.


image.png

那么二进制转成十进制是这么算的:


image.png
定义一个res用来返回结果,每当遍历到一个新的节点,就把前面res的值*2再加上当前节点的值:
image.png
这样第一个1一共乘了四个2,第二个1一共乘了一个2,加在一起正好是返回的结果。
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        res = 0
        cur = head
        while cur:
            res = res * 2 + cur.val
            cur = cur.next
        return res

中等

(1)删除节点

82. 删除排序链表中的重复元素 II

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        mydict = {}
        cur = head
        newhead = ListNode(0)
        newhead.next = head
        while cur:
            if cur.val in mydict:
                mydict[cur.val] += 1
            else:
                mydict[cur.val] = 1
            cur = cur.next
        cur = newhead
        nex = cur.next
        while nex:
            if mydict[nex.val] == 1:
                cur.next = nex
                cur = cur.next
            nex = nex.next
        cur.next = None
        return newhead.next

因为是排序链表,还可以使用三指针:
参考:
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/solution/chao-qing-xi-tu-jie-san-zhi-zhen-fa-by-justdo1t/

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        newhead = ListNode(0)
        newhead.next = head
        cur, left, right = newhead, newhead.next, newhead.next
        while right:
            while right.next and right.next.val == right.val:
                right = right.next
            if right == left:
                cur.next = left
                cur = cur.next
            left = right.next
            right = left
        cur.next = None
        return newhead.next
        

19. 删除链表的倒数第N个节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if not head or not head.next:
            return None
        slow, fast = head, head
        while n > 0:
            fast = fast.next
            n -= 1
        if not fast:
            return head.next
        while fast and fast.next:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return head

(2)变换链表

24. 两两交换链表中的节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        
        cur1, cur2 = head, head.next
        nex = cur2.next
        newhead = ListNode(0)
        newhead.next = head
        cur = newhead
        while cur1 and cur2:
            cur.next = cur2
            cur2.next = cur1
            cur = cur1
            cur.next = None
            cur1 = nex
            if cur1 and cur1.next:
                cur2 = cur1.next
            else:
                break
            nex = cur2.next
        if cur1:
            cur.next = cur1
        return newhead.next

61. 旋转链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if k == 0 or not head:
            return head
        lenth = 0
        h = head
        while h:
            lenth += 1
            h = h.next
        lenth = k % lenth
        if lenth == 0:
            return head
        fast = head
        slow = head
        while lenth > 0:
            fast = fast.next
            lenth -= 1
        pivot = fast
        while fast and fast.next:
            fast = fast.next
            slow = slow.next
            pivot = pivot.next
        newhead = slow.next
        slow.next = None
        pivot.next = head
        return newhead

148. 排序链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def sortList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        fast, slow = head.next, head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        right_head = slow.next
        slow.next = None
        left, right = self.sortList(head), self.sortList(right_head)
        return self.merge(left, right)

    # 合并两个链表
    def merge(self, head1, head2):
        h1, h2 = head1, head2
        newhead = ListNode(0)
        cur = newhead
        while h1 and h2:
            if h1.val > h2.val:
                cur.next = h2   
                h2 = h2.next
            else:
                cur.next = h1
                h1 = h1.next
            cur = cur.next
        cur.next = h1 or h2
        return newhead.next

86. 分隔链表

面试题 02.04. 分割链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def partition(self, head: ListNode, x: int) -> ListNode:
        before, after = ListNode(0), ListNode(0)
        cur1, cur2 = before, after
        h = head
        while h:
            if h.val < x:
                cur1.next = h
                cur1 = cur1.next
            else:
                cur2.next = h
                cur2 = cur2.next
            h = h.next
        cur2.next = None
        cur1.next = after.next
        return before.next

92. 反转链表 II

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
        newhead = ListNode(0)
        newhead.next = head
        pre = newhead
        for _ in range(m - 1):
            pre = pre.next
        tmp_head = None
        cur = pre.next
        for _ in range(n - m + 1):
            nex = cur.next
            cur.next = tmp_head
            tmp_head = cur
            cur = nex
        pre.next.next = cur
        pre.next = tmp_head
        return newhead.next

109. 有序链表转换二叉搜索树

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sortedListToBST(self, head: ListNode) -> TreeNode:
        if not head:
            return None
        if not head.next:
            return TreeNode(head.val)
        fast, slow = head.next.next, head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        root = TreeNode(slow.next.val)
        root.right = self.sortedListToBST(slow.next.next)
        slow.next = None
        root.left = self.sortedListToBST(head)
        return root

328. 奇偶链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def oddEvenList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        odd_head = head
        odd_tail = head
        even_head = head.next
        even_tail = head.next
        while odd_tail.next and even_tail.next:
            odd_tail.next = even_tail.next
            odd_tail = odd_tail.next
            even_tail.next = odd_tail.next
            even_tail = even_tail.next
        odd_tail.next = even_head
        return odd_head

143. 重排链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        if not head:
            return head
        # 找到链表的中间节点
        fast, slow = head, head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        # 反转后半部分链表
        cur = slow.next
        slow.next = None
        newhead = None
        while cur:
            nex = cur.next
            cur.next = newhead
            newhead = cur
            cur = nex
        
        cur1 = head
        cur2 = newhead
        while cur1 and cur2:
            nex1 = cur1.next
            nex2 = cur2.next
            cur1.next = cur2
            cur1 = nex1
            cur2.next = cur1
            cur2 = nex2
        return head

725. 分隔链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]:
        res = []
        lenth, extra, part_len = 0, 0, 0

        h = root
        while h:
            lenth += 1
            h = h.next

        if lenth >= k:
            extra = lenth % k
            part_len = lenth // k
        else:
            part_len = 1

        cur, nex = root, root
        while k > 0:
            tmp_lenth = 0
            k -= 1
            tmp_lenth = part_len + (extra > 0)
            extra = max(0, extra - 1)
            res.append(nex)
            while cur and tmp_lenth > 1:
                tmp_lenth -= 1
                cur = cur.next 
            if cur:
                nex = cur.next
                cur.next = None
                cur = nex          
        return res

(3)环路检测

面试题 02.08. 环路检测

142. 环形链表 II

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        fast, slow = head, head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                fast = head
                while slow != fast:
                    fast = fast.next
                    slow = slow.next
                return slow            
        return None

(4)求值

2. 两数相加

面试题 02.05. 链表求和

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        res, flag = 0, 0
        tmp1, tmp2 = l1, l2
        newhead = ListNode(0)
        cur = newhead
        while tmp1 and tmp2:
            cur.next = ListNode((tmp1.val + tmp2.val + flag) % 10)
            flag = (tmp1.val + tmp2.val + flag) // 10
            cur = cur.next
            tmp1, tmp2 = tmp1.next, tmp2.next
        while tmp1:
            cur.next = ListNode((tmp1.val + flag) % 10)
            flag = (tmp1.val + flag) // 10
            cur = cur.next
            tmp1 = tmp1.next
        while tmp2:
            cur.next = ListNode((tmp2.val + flag) % 10)
            flag = (tmp2.val + flag) // 10
            cur = cur.next
            tmp2 = tmp2.next
        if flag > 0:
            cur.next = ListNode(flag)
        return newhead.next

445. 两数相加 II

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        stack1, stack2 = [], []
        cur = l1
        while cur:
            stack1.append(cur.val)
            cur = cur.next
        cur = l2
        while cur:
            stack2.append(cur.val)
            cur = cur.next
        flag = 0
        newhead = None
        while stack1 or stack2 or flag != 0 :
            cur1, cur2 = 0, 0
            if stack1:
                cur1 = stack1.pop()
            if stack2:
                cur2 = stack2.pop()
            tmp = cur1 + cur2 + flag
            flag = tmp // 10
            tmp %= 10
            cur = ListNode(tmp)
            cur.next = newhead
            newhead = cur
        return newhead

817. 链表组件

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def numComponents(self, head: ListNode, G: List[int]) -> int:
        mydict = {}
        for i in G:
            if i not in mydict:
                mydict[i] = True
        cur = head
        res = 0
        flag = 0
        while cur:
            if cur.val in mydict and flag == 0:
                res += 1
                flag = 1
            elif cur.val not in mydict:
                flag = 0
            cur = cur.next
        return res

其他

1019. 链表中的下一个更大节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def nextLargerNodes(self, head: ListNode) -> List[int]:
        res, stack = [], []
        index = 0
        cur = head
        while cur:
            res.append(0)
            while stack and cur.val > stack[-1][0].val:
                node = stack.pop()
                res[node[1]] = cur.val
            stack.append([cur,index])
            cur = cur.next
            index += 1
        return res

1367. 二叉树中的列表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
        if not root:
            return False
        return self.helper(head, root) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right)

    def helper(self, head, root):
        if not head:
            return True
        if not root:
            return False
        if head.val != root.val:
            return False
        return self.helper(head.next, root.left) or self.helper(head.next, root.right)

1171. 从链表中删去总和值为零的连续节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeZeroSumSublists(self, head: ListNode) -> ListNode:
        mydict = {}
        mysum = 0
        newhead = ListNode(0)
        cur = newhead
        newhead.next = head
        while cur:
            mysum += cur.val
            mydict[mysum] = cur
            cur = cur.next
        
        mysum = 0
        cur = newhead
        while cur:
            mysum += cur.val
            cur.next = mydict[mysum].next
            cur = cur.next
        return newhead.next

138. 复制带随机指针的链表

剑指 Offer 35. 复杂链表的复制

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""

class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if not head:
            return None
        newhead = Node(0)
        cur = newhead
        tmp = head

        num = 0
        mydict_node_to_index = {}
        index_to_mynewnode = {}
        while tmp:
            cur.next = Node(tmp.val)
            cur = cur.next
            mydict_node_to_index[tmp] = num
            index_to_mynewnode[num] = cur
            num += 1
            tmp = tmp.next

        index_to_random_index = {}
        tmp = head
        while tmp:
            index_to_random_index[mydict_node_to_index[tmp]] = None if not tmp.random else mydict_node_to_index[tmp.random]
            tmp = tmp.next
        
        cur = newhead.next
        num = 0
        while cur:
            if index_to_random_index[num] is not None:
                cur.random = index_to_mynewnode[index_to_random_index[num]]
            cur = cur.next
            num += 1

        return newhead.next

一样的写法:

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""
class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if not head:
            return None

        newhead = Node(0)
        cur = newhead
        tmp = head
        node_to_index = {}
        index_to_newhead = {}
        num = 0
        while tmp:
            cur.next = Node(tmp.val)
            cur = cur.next
            index_to_newhead[num] = cur
            node_to_index[tmp] = num
            num += 1
            tmp = tmp.next
        
        index_to_random_index = {}
        num = 0
        tmp = head
        while tmp:
            index_to_random_index[num] = node_to_index[tmp.random] if tmp.random is not None else None
            tmp = tmp.next
            num += 1
        
        cur = newhead.next
        num = 0
        while cur:
            if index_to_random_index[num] is not None:
                cur.random = index_to_newhead[index_to_random_index[num]]
            cur = cur.next
            num += 1
        return newhead.next

430. 扁平化多级双向链表

具体实现看代码吧。
注意1是要把原来的child置为空,2是prev要有指向。
要是写完发现节点的顺序是对的,但是不是一个有效的双向链表估计就是注意1和2的问题,用循环打印一下当前节点的值和当前节点的prev值看看是不是有没连上的。

"""
# Definition for a Node.
class Node:
    def __init__(self, val, prev, next, child):
        self.val = val
        self.prev = prev
        self.next = next
        self.child = child
"""

class Solution:
    def flatten(self, head: 'Node') -> 'Node':
        if not head:
            return head
        cur = head
        while cur:
            if cur.child:
                self.helper(cur)
            cur = cur.next
        return head
    
    def helper(self, node):
        right = node.next
        node.next = node.child
        node.child.prev = node
        node.child = None
        while node.next:
            if node.child:
                self.helper(node)
            node = node.next
        node.next = right
        if right:
            right.prev = node
        return node

147. 对链表进行插入排序

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def insertionSortList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        newhead = ListNode(float('-inf'))
        tail = newhead
        cur = head
        nex = cur
        while cur:
            nex = nex.next
            if cur.val < tail.val:
                tmp = newhead
                while cur.val > tmp.val and cur.val > tmp.next.val:
                    tmp = tmp.next
                cur.next = tmp.next
                tmp.next = cur
            else:
                tail.next = cur
                tail = tail.next
                tail.next = None
            cur = nex
        return newhead.next

困难

23. 合并K个排序链表

解法一:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        heap = []
        for i in lists:
            while i:
                heapq.heappush(heap,i.val)
                i = i.next
        head = ListNode(0)
        cur = head
        while heap:
            cur.next = ListNode(heap[0])
            heapq.heappop(heap)
            cur = cur.next
        return head.next

其他解法待更新~

25. K 个一组翻转链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        newhead = ListNode(0)
        newhead.next = head
        pre = newhead
        cur = head
        while cur: 
            tail = cur
            for i in range(1, k):
                tail = tail.next
                if not tail:
                    return newhead.next
            nex = tail.next
            cur, tail = self.helper(cur, tail)
            pre.next = cur
            tail.next = nex
            pre = tail
            cur = tail.next
        return newhead.next

    def helper(self, head, tail):
        pre = tail.next
        tmp = head
        while pre != tail:
            nex = tmp.next
            tmp.next = pre
            pre = tmp
            tmp = nex
        return tail, head
上一篇 下一篇

猜你喜欢

热点阅读