예제 #1
0
파일: Sort List.py 프로젝트: chyt123/cosmos
 def sortList(self, head: ListNode) -> ListNode:
     if not head or not head.next:
         return head
     if not head.next.next:
         if head.val > head.next.val:
             nxt = head.next
             head.next.next = head
             head.next = None
             return nxt
         return head
     rtn = ListNode()
     rtn.next = head
     slow = fast = rtn
     while fast and fast.next:
         slow = slow.next
         fast = fast.next.next
     right = self.sortList(slow.next)
     slow.next = None
     left = self.sortList(head)
     rtn = tmp = ListNode()
     while left and right:
         if left.val <= right.val:
             tmp.next = left
             left = left.next
         else:
             tmp.next = right
             right = right.next
         tmp = tmp.next
     tmp.next = left if left else right
     return rtn.next
예제 #2
0
    def reverseBetween(self, head: ListNode, left: int,
                       right: int) -> ListNode:
        if left == right:
            return head
        rtn = ListNode()
        rtn.next = head
        start = rtn
        cnt = 1
        while head and cnt != left:
            start = head
            head = head.next
            cnt += 1

        pre = None
        while head and cnt != right:
            nxt = head.next
            head.next = pre
            pre = head
            head = nxt
            cnt += 1

        if head:
            start.next.next = head.next
            head.next = pre
            start.next = head

        return rtn.next
 def test_2_add(self):
     for case in self.cases:
         l1, l2, result = case
         n1 = ListNode.of(l1)
         n2 = ListNode.of(l2)
         res = ListNode.of(result)
         self.assertEqual(self.solution.addTwoNumbers(n1, n2), res)
예제 #4
0
 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
     carry, head, tail = 0, None, None
     while l1 or l2 or carry:
         d1, d2 = l1.val if l1 else 0, l2.val if l2 else 0
         if not head:
             head = ListNode((d1 + d2 + carry) % 10)
             tail = head
         else:
             tail.next = ListNode((d1 + d2 + carry) % 10)
             tail = tail.next
         carry = (d1 + d2 + carry) // 10
         l1, l2 = l1.next if l1 else l1, l2.next if l2 else l2
     return head
예제 #5
0
 def swapPairs(self, head: ListNode) -> ListNode:
     cur = ListNode()
     rtn = cur
     while head and head.next:
         new_head = head.next.next
         cur.next = head.next
         head.next.next = head
         head.next = None
         cur = head
         head = new_head
     if head:
         cur.next = head
     return rtn.next
예제 #6
0
 def removeElements(self, head, val):
     """
     :type head: ListNode
     :type val: int
     :rtype: ListNode
     """
     phead = ListNode(0)
     phead.next = head
     p = phead
     while p:
         while p.next and p.next.val == val:
             p.next = p.next.next
         p = p.next
     return phead.next
예제 #7
0
def lc_list2singlelinkedlistwithloop(l: List, pos: int) -> ListNode:
    ret = ListNode(l[0])
    cur = ret
    for i in range(0, len(l)):
        if i == 0:
            if i == pos:
                conn = cur
            continue
        cur.next = ListNode(l[i])
        cur = cur.next
        if i == pos:
            conn = cur
    cur.next = conn
    return ret
예제 #8
0
 def partition(self, head: ListNode, x: int) -> ListNode:
     s_pt = s_cur = ListNode()
     l_pt = l_cur = ListNode()
     while head:
         tmp = head.next
         if head.val < x:
             s_cur.next = head
             s_cur = s_cur.next
         else:
             l_cur.next = head
             l_cur = l_cur.next
         head.next = None
         head = tmp
     s_cur.next = l_pt.next
     return s_pt.next
예제 #9
0
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        """
        迭代法求解;
        有几步关键:1. 构建虚拟头部,2.构建一个可以移动的指针,通过每次更新指针来操作下一个元素
        :param l1:
        :param l2:
        :return:
        """
        pre_head = ListNode(0)
        node = pre_head
        while l1 is not None and l2 is not None:
            if l1 is not None and l2 is not None:
                if l1.val <= l2.val:
                    node.next = l1
                    l1 = l1.next
                else:
                    node.next = l2
                    l2 = l2.next
                # 这一步很关键,为了修改node的当前位置,使之向下走一个
                node = node.next

        # 最多可能会出现其中一个没有合并完的情况,拼接上去
        node.next = l1 if l1 is not None else l2
        # 去掉虚构的头部
        return pre_head.next
예제 #10
0
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        nhead = ListNode(-1, head)
        curr_ptr = nhead

        while curr_ptr is not None:
            # print_link(nhead)

            curr_tail = curr_ptr

            reverse = True
            for _ in range(k):
                curr_tail = curr_tail.next
                if curr_tail is None:
                    reverse = False
                    break
            next_head = curr_ptr.next
            if reverse:
                # 我傻了,怎么翻转
                for _ in range(k - 1):
                    t = curr_ptr.next
                    curr_ptr.next = t.next
                    t.next = curr_tail.next
                    curr_tail.next = t
                # print_link(nhead)
            else:
                break

            curr_ptr = next_head
        return nhead.next
예제 #11
0
 def swapPairs(self, head):
     vhead = ListNode(0)
     vhead.next = head
     left = vhead
     middle = head
     right = None
     while middle is not None:
         right = middle.next
         if right is None:
             break
         middle.next = right.next
         left.next = right
         right.next = middle
         left = middle
         middle = left.next
     return vhead.next
예제 #12
0
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        # if not l1 or not l2:
        #     return l1 if l1 else l2
        dummy = ListNode(0)
        rtn = dummy

        while l1 and l2:
            if l1.val <= l2.val:
                dummy.next = l1
                l1 = l1.next
            else:
                dummy.next = l2
                l2 = l2.next
            dummy = dummy.next
        dummy.next = l1 if l1 else l2
        return rtn.next
 def deleteDuplicates(self, head: ListNode) -> ListNode:
     if not head:
         return None
     sp = ListNode()
     sp.next = head
     pt = head
     pre = sp
     while pt and pt.next:
         if pt.val == pt.next.val:
             while pt.next and pt.val == pt.next.val:
                 pt.next = pt.next.next
             pre.next = pt.next
             pt = pre.next
         else:
             pre = pt
             pt = pt.next
     return sp.next
예제 #14
0
 def mergeTwoListsRecursion(self, l1: ListNode, l2: ListNode) -> ListNode:
     """
     递归解法
     :param l1:
     :param l2:
     :return:
     """
     if l1 is None:
         return l2
     if l2 is None:
         return l1
     if l1.val <= l2.val:
         l1.next = self.mergeTwoLists(l1.next, l2)
         return l1
     else:
         l2.next = self.mergeTwoLists(l1, l2.next)
         return l2
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        dummy = ListNode(0)
        dummy.next = head

        pre = dummy
        end = dummy
        while end.next is not None:
            for i in range(k):
                end = end.next if end is not None else None
            if end is None:
                break
            start = pre.next
            next = end.next
            end.next = None
            pre.next = self.reverse(start)
            start.next = next
            pre, end = start, start
        return dummy.next
예제 #16
0
 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
     # O(n) time & O(1) space
     if not l1:
         return l2
     elif not l2:
         return l1
     num1, num2 = 0, 0
     while l1 or l2:
         num1 = num1 * 10 + l1.val if l1 else num1
         num2 = num2 * 10 + l2.val if l2 else num2
         l1 = l1.next if l1 else l1
         l2 = l2.next if l2 else l2
     head, num = None, num1 + num2
     if num == 0:
         return ListNode(0)
     while num:
         head, num = ListNode(num % 10, head), num // 10
     return head
 def deleteDuplicates(self, head: ListNode) -> ListNode:
     rtn = head
     while head:
         if head.next and head.val == head.next.val:
             nxt = head.next
             head.next = head.next.next
             del nxt
         else:
             head = head.next
     return rtn
예제 #18
0
 def reverseList(self, head: ListNode) -> ListNode:
     if not head:
         return head
     pre, cur = head, head.next
     head.next = None
     while cur:
         nxt = cur.next
         cur.next = pre
         cur, pre = nxt, cur
     return pre
예제 #19
0
 def addTwoNumbers(self, l1, l2):
     pL1 = l1
     pL2 = l2
     addOneDigit = False
     result = None
     cur = None
     while pL1 is not None and pL2 is not None:
         val = pL1.val + pL2.val
         if addOneDigit is True:
             val = val + 1
             addOneDigit = False
         if val >= 10:
             addOneDigit = True
             val = val - 10
         n = ListNode(val)
         if result is None:
             result = n
         else:
             cur.next = n
         cur = n
         pL1 = pL1.next
         pL2 = pL2.next
     if pL1 is not None:
         cur.next = pL1
     if pL2 is not None:
         cur.next = pL2
     while addOneDigit is True:
         t = cur
         cur = cur.next
         if cur is None:
             node = ListNode(1)
             t.next = node
             addOneDigit = False
         else:
             val = cur.val + 1
             if val >= 10:
                 cur.val = val - 10
                 addOneDigit = True
             else:
                 addOneDigit = False
                 cur.val = val
     return result
예제 #20
0
 def mergeKLists(self, lists: List[ListNode]) -> ListNode:
     # 将所有节点加入到一个列表中
     nodes = []
     for i in range(len(lists)):
         while lists[i] is not None:
             # 必须要重新建立对象listnode,否则会产生引用不对的问题(.next)
             nodes.append(ListNode(lists[i].val))
             lists[i] = lists[i].next
     # 建立最小堆
     nodeHeap = NodeHeap(False)
     l = nodeHeap.build_max_heap(nodes)
     # 逐个从最小堆中取出元素
     pre_head = ListNode(0)
     moving_node = pre_head
     node = nodeHeap.pop(l)
     while node is not None:
         moving_node.next = node
         moving_node = moving_node.next
         node = nodeHeap.pop(l)
     return pre_head.next
예제 #21
0
    def oddEvenList(self, head: ListNode) -> ListNode:
        odd_head = odd = ListNode()
        even_head = even = ListNode()
        cnt = 1
        while head:
            if cnt % 2 != 0:
                odd.next = head
                odd = odd.next
            else:
                even.next = head
                even = even.next
            head = head.next
            cnt += 1

        if cnt % 2 != 0:
            odd.next = None
        else:
            even.next = None
        odd.next = even_head.next
        return odd_head.next
 def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
     rtn = ListNode()
     rtn.next = head
     mem = [rtn]
     slow = fast = head
     scnt = fcnt = 0
     while fast and fast.next:
         mem.append(slow)
         slow = slow.next
         scnt += 1
         fast = fast.next.next
         fcnt += 2
     fcnt += 0 if not fast else 1
     idx = fcnt - n + 1
     while len(mem) < idx + 2 and slow:
         mem.append(slow)
         slow = slow.next
     if len(mem) < idx + 2:
         mem.append(None)
     mem[idx - 1].next = mem[idx + 1]
     return rtn.next
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """

        last = head = ListNode(0)
        carry = 0
        n1 = l1
        n2 = l2

        while n1 is not None and n2 is not None:
            val = carry + n1.val + n2.val
            last.next = ListNode(val % 10)
            carry = val // 10

            last = last.next
            n1 = n1.next
            n2 = n2.next

        if n1 is None and n2 is None:
            rest = None
        elif n1 is None:
            rest = n2
        else:
            rest = n1

        while rest is not None:
            val = carry + rest.val
            last.next = ListNode(val % 10)
            carry = val // 10

            last = last.next
            rest = rest.next

        if carry != 0:
            last.next = ListNode(carry)

        return head.next
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """

        last = head = ListNode(0)
        carry = 0

        while l1 or l2 or carry != 0:
            if l1:
                carry += l1.val
                l1 = l1.next
            if l2:
                carry += l2.val
                l2 = l2.next
            last.next = ListNode(carry % 10)
            last = last.next
            carry = carry // 10

        return head.next
예제 #25
0
    def mergeKLists(self, lists) -> ListNode:

        lists=[item for item in lists if item!=None]
        heapq.heapify(lists)
        result=ListNode(0)
        curr=result

        while lists:
            min_node=heapq.heappop(lists)
            curr.next=min_node
            curr=min_node
            if min_node.next!=None:
                heapq.heappush(lists,min_node.next)
        return result.next
예제 #26
0
    def reverseKGroup(self, head, k):
        if k < 2:
            return head
        vhead = ListNode(0)
        vhead.next = head

        #search for next k nodes
        def hasNodes(nodeHead, numNodes):
            c = nodeHead.next
            while numNodes > 0:
                if c is None:
                    return False
                c = c.next
                numNodes = numNodes - 1
            return True

        def reverseNodes(nodeHead, numNodes):
            c0 = nodeHead
            c1 = c0.next
            c2 = c1.next
            c3 = c1
            n = numNodes - 1
            while n > 0:
                t = c2.next
                c2.next = c1
                c0.next = c2
                c1 = c2
                c2 = t
                n = n - 1
            c3.next = t
            return c3

        cur = vhead
        while hasNodes(cur, k) is True:
            cur = reverseNodes(cur, k)
        return vhead.next
예제 #27
0
 def insertionSortList(self,
                       head: Optional[ListNode]) -> Optional[ListNode]:
     dummy = ListNode(-5001)
     dummy.next = to_insert = head
     while head and head.next:
         if head.val > head.next.val:
             to_insert = head.next
             pre = dummy
             while pre.next.val < to_insert.val:
                 pre = pre.next
             head.next = to_insert.next
             to_insert.next = pre.next
             pre.next = to_insert
         else:
             head = head.next
     return dummy.next
 def swapPairs(self, head: ListNode) -> ListNode:
     if head is None or head.next is None:
         return head
     pre_head = ListNode(0)
     moving_node = pre_head
     node = head
     while node is not None and node.next is not None:
         moving_node.next = node.next
         # 获取第三个结点
         temp = node.next.next
         # 指向调换后的最后一个结点
         moving_node.next.next = node
         # 移动,更新指向
         node.next = temp
         moving_node = moving_node.next.next
         node = node.next
     return pre_head.next
예제 #29
0
    def mergeKListsDict(self, lists: List[ListNode]) -> ListNode:
        """
        使用一个字典保存每个node的位置
        时间复杂度:O(NK),N为所有元素个数和,K为lists链表元素个数
        :param lists:
        :return:
        """
        index_dict = {}
        pre_head = ListNode(0)
        moving_node = pre_head
        for i in range(len(lists)):
            if lists[i] is not None:
                index_dict[i] = i
        while len(index_dict) > 0:
            index = None
            minimum_node = None
            for key, value in index_dict.items():
                if minimum_node is None:
                    index = key
                    minimum_node = lists[value]
                else:
                    if lists[value].val < minimum_node.val:
                        index = key
                        minimum_node = lists[value]

            # 更新对应item的listnode
            if lists[index] is not None:
                lists[index] = lists[index].next
                if lists[index] is None:
                    index_dict.pop(index)

                # 保存结果
                moving_node.next = minimum_node
                moving_node = moving_node.next
            else:
                index_dict.pop(index)

        return pre_head.next
예제 #30
0
        def merge_sort(node: ListNode) -> ListNode:
            if node is None:
                return None
            if node.next is None:
                return node
            nnode = ListNode(-1, node)
            t1 = nnode
            t2 = nnode
            while t2 is not None and t2.next is not None:
                t1 = t1.next
                t2 = t2.next
                t2 = t2.next
            t = t1
            t1 = t1.next
            t.next = None

            # print_link(node)
            # print_link(t1)

            h1 = merge_sort(node)
            h2 = merge_sort(t1)
            # print_link(h1)
            # print_link(h2)
            return merge(h1, h2)