Ejemplo n.º 1
0
 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
Ejemplo n.º 2
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
Ejemplo n.º 3
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
Ejemplo n.º 4
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
Ejemplo n.º 5
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
Ejemplo n.º 6
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
Ejemplo n.º 7
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
Ejemplo n.º 8
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
Ejemplo n.º 9
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
Ejemplo n.º 10
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
Ejemplo n.º 11
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
    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
Ejemplo n.º 13
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
    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
Ejemplo n.º 15
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
Ejemplo n.º 16
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
Ejemplo n.º 17
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
Ejemplo n.º 18
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
Ejemplo n.º 19
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
 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
    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
 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
Ejemplo n.º 24
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
Ejemplo n.º 25
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
Ejemplo n.º 26
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)
Ejemplo n.º 27
0
Explanation: 342 + 465 = 807.
'''

from util import ListNode, printListNode

#class ListNode(object):
#    def __init__(self, x):
#        self.val = x
#        self.next = None
#
#def printListNode(head):
#    while (head):
#        print head.val
#        head = head.next

node11 = ListNode(2)
node12 = ListNode(4)
node13 = ListNode(6)
node11.next = node12
node12.next = node13
'''
1: pre, 2(p)->4->6
    1.1: 2(p)->4(tmp)->6
    1.2: None(pre)<-2(p)  4->6
    1.3: None<-2(prev/p)  4->6
    1.4: None<-2(pre)  4(p)->6

2: None<-2(prev) 4(p)->6
    2.1: None<-2(prev)  4(p)->6(tmp)
    2.2: None<-2(prev)<-4(p)  6(tmp)
    2.3: None<-2<-4(prev/p)  6
Ejemplo n.º 28
0
setattr(ListNode, "__lt__", lambda self, other: self.val <= other.val if other !=None else False)
class Solution:
    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

sol=Solution()


l13=ListNode(4,None)
l12=ListNode(3,l13)
l11=ListNode(2,l12)

l23=ListNode(6,None)
l22=ListNode(5,l23)
l21=ListNode(4,l22)

print("output {} ".format(str_list(sol.mergeKLists([l21,l11]))))
Ejemplo n.º 29
0
        return l

    def push(self, l: List, item) -> None:
        l.append(item)
        size = len(l)
        self.heap_adjust(l, size // 2, size)

    def pop(self, l: List):
        if len(l) == 0:
            return None
        elif len(l) == 1:
            return l.pop(0)
        item = l.pop(len(l) - 1)
        res = l[0]
        l[0] = item
        self.heap_adjust(l, 0, len(l))
        return res


if __name__ == '__main__':
    heap = NodeHeap(False)
    l = [2, 3, 41, 5, 7, 1]
    nodes = []
    for i in range(len(l)):
        nodes.append(ListNode(l[i]))
    max_heap = heap.build_max_heap(nodes)
    v = heap.pop(max_heap)
    while v is not None:
        print(v.val, end=', ')
        v = heap.pop(max_heap)