def addTwoNumbers(self, l1, l2): ''' :param l1: :param l2: :return: ''' p = dummy = ListNode(-1) carry = 0 while l1 or l2 or carry: val = (l1 and l1.val or 0) + (l2 and l2.val or 0) + carry carry = val / 10 p.next = ListNode(val % 10) l1 = l1 and l1.next l2 = l2 and l2.next p = p.next return dummy.next
def answer(l1, l2): carry = 0 zero_node = node = ListNode(0) while l1 or l2 or carry: if l1 is not None: carry += l1.val l1 = l1.next if l2 is not None: carry += l2.val l2 = l2.next node.next = ListNode(carry % 10) node = node.next carry //= 10 return zero_node.next
def merge_k_lists(lists): dummy = ListNode(None) curr = dummy q = queuelib.PriorityQueue() for node in lists: if node: q.put((node.val, node)) while q.qsize() > 0: curr.next = q.get()[1] curr = curr.next if curr.next: q.put((curr.next.val, curr.next)) return dummy.next
def mergeTwoList(l1, l2): res = ListNode(0) cur = res while l1 and l2: if l1.val <= l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return res.next
def mergeKLists(lists): dummy = node = ListNode(0) h = [(n.val, n) for n in lists if n] heapify(h) while h: v, n = h[0] if n.next is None: heappop(h) #only change heap size when necessary else: heapreplace(h, (n.next.val, n.next)) node.next = n node = node.next return dummy.next
def solution(self, head): if head is None or head.next is None or head.next.next is None: return # 두개의 포인터로 단일 리스트 중간 노드를 찾은뒤 두 리스트를 반절로 나눕니다. # 1->2->3->4 => 1->2, 3->4 slow = fast = head while fast.next and fast.next.next: slow = slow.next fast = fast.next.next head2 = slow.next slow.next = None # 후반 절반의 리스트의 순서를 거꾸로 합니다. # 3->4 => 4->3 temp_head = ListNode() temp_head.next = head2 p = head2.next head2.next = None while p: tmp = p p = p.next tmp.next = temp_head.next temp_head.next = tmp head2 = temp_head.next # 두 절반을 섞어가면서 합쳐줍니다. # 1->2, 4->3 => 1->4->2->3 p1 = head p2 = head2 while p2: t1 = p1.next p1.next = p2 t2 = p2.next p2.next = t1 p1 = t1 p2 = t2
def mergeTwoLists(self, l1, l2): nHead = ListNode(0) lt, rt, backHead = l1, l2, nHead while lt or rt: if lt is None: nHead.next, rt = rt, rt.next elif rt is None: nHead.next, lt = lt, lt.next elif lt.val < rt.val: nHead.next, lt = lt, lt.next else: nHead.next, rt = rt, rt.next nHead = nHead.next return backHead.next
def create_list_node(nums): first = node = ListNode(nums[0]) for i in nums[1:]: node.next = ListNode(i) node = node.next return first
# -*- coding = utf-8 -*- # @Time:2021-01-19 10:43 # @Author:来瓶安慕嘻 # @File:力扣21_合并两个有序链表.py # @开始美好的一天吧 @Q_Q@ from Cython.Compiler.ExprNodes import ListNode def mergeTwoList(l1, l2): res = ListNode(0) cur = res while l1 and l2: if l1.val <= l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return res.next l1 = ListNode(1) l2 = ListNode(4) print(mergeTwoList(l1, l2))