from LeetCode.Python.BaseListNode import MakeListNodes, PrintListNode, ListNode


class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummy = ListNode(0)
        curr_node = dummy

        while l1 and l2:
            if l1.val > l2.val:
                curr_node.next = l2
                l2 = l2.next
            else:
                curr_node.next = l1
                l1 = l1.next

            curr_node = curr_node.next

        if l1 is None:
            curr_node.next = l2
        else:
            curr_node.next = l1

        return dummy.next


if __name__ == '__main__':
    PrintListNode(Solution().mergeTwoLists(MakeListNodes([1, 3, 4]), MakeListNodes([1, 2, 4])))
    PrintListNode(Solution().mergeTwoLists(None, None))
from LeetCode.Python.BaseListNode import MakeListNodes, PrintListNode, ListNode


class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if head is None or head.next is None:
            return head

        node_list = list()
        while head:
            node_list.append(head)
            head = head.next

        # 分为奇列表和偶列表,末尾节点补None为了方便
        odd_list = node_list[::2] + [None]
        even_list = node_list[1::2] + [None]

        # 头为偶列表的第一个节点
        # 重排的顺序为: even[0] -> odd[0] -> even[1] -> odd[1] -> ....
        result = even_list[0]
        for i in range(len(even_list) - 1):
            even_list[i].next = odd_list[i]
            odd_list[i].next = even_list[i + 1] if even_list[i + 1] else (odd_list[i + 1] if odd_list[i + 1] else None)

        return result


if __name__ == '__main__':
    PrintListNode(Solution().swapPairs(MakeListNodes([1, 2, 3, 4])))
    PrintListNode(Solution().swapPairs(MakeListNodes([1, 2, 3])))
from LeetCode.Python.BaseListNode import MakeListNodes, PrintListNode, ListNode


class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head:
            return head

        # 先整个循环链表
        length = 1
        start = end = head
        while end.next:
            length += 1
            end = end.next
        end.next = start

        # 计算要移动的步数
        # 需要做一下转换
        right_step = length - k % length
        for _ in range(right_step):
            start = start.next
            end = end.next

        end.next = None
        return start


if __name__ == '__main__':
    PrintListNode(Solution().rotateRight(MakeListNodes([0, 1, 2]), 4))
    PrintListNode(Solution().rotateRight(MakeListNodes([1, 2, 3, 4, 5]), 2))
    #     return head

    def reorderList(self, head: ListNode):
        """
        Do not return anything, modify head in-place instead.
        """
        if not head:
            return

        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next

        curr_node, prev_node = slow, None
        while curr_node:
            curr_node.next, prev_node, curr_node = prev_node, curr_node, curr_node.next

        odd_head = head
        even_head = prev_node
        while even_head.next:
            odd_head.next, odd_head = even_head, odd_head.next
            even_head.next, even_head = odd_head, even_head.next
        return head


if __name__ == '__main__':
    PrintListNode(Solution().reorderList(None))
    PrintListNode(Solution().reorderList(MakeListNodes([1, 2, 3, 4])))
    PrintListNode(Solution().reorderList(MakeListNodes([1, 2, 3, 4, 5])))
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        from queue import PriorityQueue

        node_queue = PriorityQueue()
        for index, node in enumerate(lists):
            node_queue.put((node.val, index, node)) if node else ...

        dummy = ListNode(0)
        curr_node = dummy
        while not node_queue.empty():
            _, index, tmp_node = node_queue.get()  # 使用优先队列

            curr_node.next = tmp_node
            curr_node = curr_node.next

            node_queue.put((tmp_node.next.val, index,
                            tmp_node.next)) if tmp_node.next else ...

        return dummy.next


if __name__ == '__main__':
    PrintListNode(Solution().mergeKLists([
        MakeListNodes([1, 4, 5]),
        MakeListNodes([1, 3, 4]),
        MakeListNodes([2, 6])
    ]))

    PrintListNode(Solution().mergeKLists([None]))
class Solution:
    def sortedListToBST(self, head: ListNode) -> TreeNode:
        if not head:
            return None
        elif head.next is None:  # head的下一个节点为None,则它为叶子节点
            return TreeNode(head.val)

        fast_node = slow_node = pre_node = head  # pre_node用来记录中间那个节点的前一个节点
        while fast_node and fast_node.next:
            pre_node = slow_node
            fast_node, slow_node = fast_node.next.next, slow_node.next

        pre_node.next = None  # 将中间节点父节点的子节点截断

        root = TreeNode(slow_node.val)  # root节点为中间节点
        root.left = self.sortedListToBST(head)  # 递归左节点
        root.right = self.sortedListToBST(slow_node.next)  # 递归右节点

        return root


if __name__ == '__main__':
    # res = Solution().sortedListToBST(None)
    # res = Solution().sortedListToBST(MakeListNodes([-10, -3, 0, 5, 9]))
    res = Solution().sortedListToBST(
        MakeListNodes([
            -93, -89, -85, -76, -56, -53, -20, -10, 20, 28, 41, 50, 66, 70, 87,
            88, 91, 94
        ]))
    pass
Esempio n. 7
0
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

from LeetCode.Python.BaseListNode import MakeListNodes, PrintListNode, ListNode


class Solution:
    def sortList(self, head: ListNode) -> ListNode:
        node_list = list()
        while head:
            node_list.append(head)
            head = head.next

        node_list.sort(key=lambda x: x.val)

        length = len(node_list)
        node_list.append(None)

        for index in range(length):
            node_list[index].next = node_list[index + 1]

        return node_list[0]


if __name__ == '__main__':
    PrintListNode(Solution().sortList(None))
    PrintListNode(Solution().sortList(MakeListNodes([4, 2, 1, 3])))
    #             return head
    #
    #         node_set.add(head)
    #         head = head.next
    #
    #     return None

    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # python2 中set的实现还不是散列表的形式,效率上比dict慢
        node_dict = dict()

        while head:
            if head in node_dict:
                return head

            node_dict.update({head: 1})
            head = head.next

        return None


if __name__ == '__main__':
    node = MakeListNodes([1, 2, 3, 4, 5, 6, 7])
    node.next.next.next.next.next = node.next

    print(Solution().detectCycle(node).val)
Esempio n. 9
0
#
# [206] Reverse Linked List
#
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

from LeetCode.Python.BaseListNode import MakeListNodes, PrintListNode, ListNode


class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head:
            return

        curr_node, prev_node = head, None
        while curr_node:
            # curr_node.next, curr_node, prev_node = prev_node, curr_node.next, curr_node   # 这种方式比较耗时
            tmp = curr_node.next
            curr_node.next = prev_node
            prev_node = curr_node
            curr_node = tmp

        return prev_node


if __name__ == '__main__':
    PrintListNode(Solution().reverseList(head=MakeListNodes([1, 3, 4])))
Esempio n. 10
0
            next_larger_list.append(0)
            curr_val = head.val

            while stack and stack[-1][0] < curr_val:
                top_node = stack.pop()
                next_larger_list[top_node[1]] = curr_val

            stack.append((curr_val, index))
            index += 1
            head = head.next

        return next_larger_list


if __name__ == '__main__':
    print(Solution().nextLargerNodes(MakeListNodes([7, 2, 6, 6, 9, 4, 3])))
    print(Solution().nextLargerNodes(MakeListNodes([9, 7, 6, 7, 6, 9])))
    print(Solution().nextLargerNodes(MakeListNodes([2, 5, 5])))
    print(Solution().nextLargerNodes(MakeListNodes([2, 1, 5])))
    print(Solution().nextLargerNodes(MakeListNodes([2, 7, 4, 3, 5])))
    print(Solution().nextLargerNodes(MakeListNodes([1, 7, 5, 1, 9, 2, 5, 1])))

    # print("Use recursion")
    # print(Solution().nextLargerNodes_recursion(MakeListNodes([7, 2, 6, 6, 9, 4, 3])))
    # print(Solution().nextLargerNodes_recursion(MakeListNodes([9, 7, 6, 7, 6, 9])))
    # print(Solution().nextLargerNodes_recursion(MakeListNodes([2, 5, 5])))
    # print(Solution().nextLargerNodes_recursion(MakeListNodes([2, 1, 5])))
    # print(Solution().nextLargerNodes_recursion(MakeListNodes([2, 7, 4, 3, 5])))
    # print(Solution().nextLargerNodes_recursion(MakeListNodes([1, 7, 5, 1, 9, 2, 5, 1])))

    import json
#         self.next = None

from LeetCode.Python.BaseListNode import MakeListNodes, PrintListNode, ListNode


class Solution:
    def partition(self, head: ListNode, x: int) -> ListNode:
        if not head:
            return head

        less_part = list()
        great_part = list()

        while head:
            if head.val < x:
                less_part.append(head)
            else:
                great_part.append(head)

            head = head.next

        part_list = less_part + great_part + [None]
        for i in range(len(part_list) - 1):
            part_list[i].next = part_list[i + 1]

        return part_list[0]


if __name__ == '__main__':
    PrintListNode(Solution().partition(MakeListNodes([1, 4, 3, 2, 5, 2]), 3))
Esempio n. 12
0
            return head

        # 奇、偶节点
        odd_node = head
        even_node = head.next

        # 偶数头,最后连接用
        even_head = even_node

        # 偶数节点为末尾节点,所以判断其为None为结束标志
        while even_node:
            # 如果偶数节点存在,则奇数节点的next为偶数节点的next
            odd_node.next = even_node.next

            # 如果偶数节点的next(也就是下一个奇数节点)存在
            # 则奇数、偶数节点进行更新
            if even_node.next:
                odd_node = odd_node.next
                even_node.next = odd_node.next
            even_node = even_node.next

        # 奇数节点的末尾与偶数节点的头部连接
        odd_node.next = even_head

        return head


if __name__ == '__main__':
    PrintListNode(Solution().oddEvenList(MakeListNodes([1, 2, 3, 4, 5])))
    PrintListNode(Solution().oddEvenList(MakeListNodes([2, 1, 3, 5, 6, 4, 7])))
            else:
                if insert_node is not None:
                    node_list.append(insert_node)
                    insert_node = None

            head = head.next
        else:
            if insert_node is not None:
                node_list.append(insert_node)

        return len(node_list)

    def numComponents_2(self, head: ListNode, G: List[int]) -> int:
        prev_node = None
        component_num = 0
        G_set = set(G)  # 性能提升的关键啊!
        while head:
            if head.val in G_set:
                if prev_node is None or prev_node.val not in G_set:
                    component_num += 1
            prev_node = head
            head = head.next

        return component_num


if __name__ == '__main__':
    # print(Solution().numComponents(head=MakeListNodes([0, 1, 2, 3]), G=[0, 1, 3]))
    print(Solution().numComponents_2(head=MakeListNodes([0, 1, 2, 3]),
                                     G=[0, 1, 3]))
# @lc app=leetcode id=876 lang=python3
#
# [876] Middle of the Linked List
#
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

from LeetCode.Python.BaseListNode import MakeListNodes, PrintListNode, ListNode


class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        if not head:
            return

        fast, slow = head, head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next

        return slow


if __name__ == '__main__':
    PrintListNode(Solution().middleNode(MakeListNodes([1])))
    PrintListNode(Solution().middleNode(MakeListNodes([1, 2, 3, 4])))
    PrintListNode(Solution().middleNode(MakeListNodes([1, 2, 3, 4, 5])))
Esempio n. 15
0
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

from LeetCode.Python.BaseListNode import MakeListNodes, PrintListNode, ListNode


class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        dummy = ListNode(0)
        curr_node = dummy

        tmp_list = set()
        while head:
            if head.val in tmp_list:
                head = head.next
            else:
                tmp_list.add(head.val)
                curr_node.next = head
                curr_node = curr_node.next

        curr_node.next = None

        return dummy.next


if __name__ == '__main__':
    PrintListNode(Solution().deleteDuplicates(MakeListNodes([1, 1, 2])))
    PrintListNode(Solution().deleteDuplicates(MakeListNodes([1, 1, 2, 3, 3])))
        for part in part_list:
            if len(part) == k:
                part.reverse()
            else:
                part.append(None)

        # 将各组元素解开,最后一个元素如果不为None,则将其next元素指向None,防止构成循环链表
        part_list_new = list()
        for part in part_list:
            part_list_new.extend(part)
        if part_list_new and part_list_new[-1] is not None:
            part_list_new[-1].next = None

        # 链接前后各个元素
        for index in range(len(part_list_new)):
            if part_list_new[index] is not None and index + 1 < len(
                    part_list_new):
                part_list_new[index].next = part_list_new[index + 1]

        return part_list_new[0] if part_list_new else None


if __name__ == '__main__':
    PrintListNode(Solution().reverseKGroup(MakeListNodes([1, 2]), k=2))
    PrintListNode(Solution().reverseKGroup(MakeListNodes([1, 2, 3, 4, 5]),
                                           k=1))
    PrintListNode(Solution().reverseKGroup(MakeListNodes([1, 2, 3, 4, 5]),
                                           k=2))
    PrintListNode(Solution().reverseKGroup(MakeListNodes([1, 2, 3, 4, 5]),
                                           k=3))
# @lc app=leetcode id=234 lang=python3
#
# [234] Palindrome Linked List
#
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

from LeetCode.Python.BaseListNode import MakeListNodes, PrintListNode, ListNode


class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        node_list = list()
        while head:
            node_list.append(head.val)
            head = head.next

        return all([v1 == v2 for v1, v2 in zip(node_list, node_list[::-1])])


if __name__ == '__main__':
    print(Solution().isPalindrome(MakeListNodes([1])))
    print(Solution().isPalindrome(None))
    print(Solution().isPalindrome(MakeListNodes([1, 0, 0])))
    print(Solution().isPalindrome(MakeListNodes([1])))
    print(Solution().isPalindrome(MakeListNodes([1, 2])))
    print(Solution().isPalindrome(MakeListNodes([1, 2, 2, 1])))
        result = list()
        for i in range(k):
            # 1、如果有余数
            #   前面节点的个数 = 平均个数 + 1
            part_len = average + 1 if div else average
            div = div - 1 if div else div

            # 添加对应块的节点
            result.append(root_head)

            if root_head is None:
                continue

            for j in range(part_len - 1):
                root_head = root_head.next

            # 各块结束后,将末尾的节点的下一跳指向None
            root_pre = root_head
            root_head = root_head.next
            root_pre.next = None

        return result


if __name__ == '__main__':
    for part in Solution().splitListToParts(root=MakeListNodes(
        [1, 2, 3, 4, 5, 6, 7, 8, 9]),
                                            k=10):
        PrintListNode(part)
Esempio n. 19
0
#
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

from LeetCode.Python.BaseListNode import MakeListNodes, PrintListNode, ListNode


class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head

        # 如果头部前两个数字相同,则去除从头开始的重复数字
        if head.val == head.next.val:
            while (head.next is not None) and (head.val == head.next.val):
                head = head.next

            return self.deleteDuplicates(head.next)
        else:
            # 如果头部前两个数字不相同,则头部的下一个节点为递归后的结果
            head.next = self.deleteDuplicates(head.next)
            return head


if __name__ == '__main__':
    PrintListNode(Solution().deleteDuplicates(
        MakeListNodes([1, 2, 2, 3, 3, 4, 5])))
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

from LeetCode.Python.BaseListNode import MakeListNodes, PrintListNode, ListNode


class Solution:
    def insertionSortList(self, head: ListNode) -> ListNode:
        node_list = list()
        while head:
            node_list.append((head.val, head))
            head = head.next

        node_list.sort(key=lambda x: x[0])

        length = len(node_list)
        node_list.append((0, None))

        for index in range(length):
            node_list[index][1].next = node_list[index + 1][1]

        return node_list[0][1]


if __name__ == '__main__':
    PrintListNode(Solution().insertionSortList(None))
    PrintListNode(Solution().insertionSortList(MakeListNodes([4, 2, 1, 3])))