elif l.val < r.val: s.append(l) l = l.next elif l.val > r.val: s.append(r) r = r.next # Append the rest of l while l != None: s.append(l) l = l.next # Append the rest of r while r != None: s.append(r) r = r.next for i in range(1, len(s)): first = s[i - 1] second = s[i] first.next = second return s[0] from LINK import makeLL, printLL a = [1, 3, 5, 7, 9] b = [2, 4, 6, 8, 10] headA = makeLL(a) headB = makeLL(b) printLL(A(headA, headB))
return head # 2pass n using dummy node def B(head, n): # Use dummy to make it easy to return dummy = node(0) dummy.next = head length = 0 curr = head while curr: length += 1 curr = curr.next nodeToRem = length - n curr = dummy while nodeToRem > 0: nodeToRem -= 1 curr = curr.next curr.next = curr.next.next return dummy.next from LINK import makeLL, printLL a = [1, 2, 3, 4, 5] head = makeLL(a) printLL(A(head, 2))
# Reverse right part of LL revLeft = [] while left: revLeft.append(left.pop()) # Reorder based on constraint ret = [] while revLeft or right: if revLeft: ret.append(revLeft.pop()) if right: ret.append(right.pop()) # Assign next values for i in range(1, len(ret)): ret[i - 1].next = ret[i] ret[-1].next = None # Return head return head # a=[1,2,3,4] # [1,4,2,3] # a=[1,2,3,4,5] # [1,5,2,4,3] a = [1, 2, 3, 4, 5, 6] # [1,6,2,5,3,4] from LINK import makeLL, printLL head = makeLL(a) head = A(head) printLL(head)
if not ret: return ret[0] = node(ret[0]) # kntime for i in range(1,len(ret)): ret[i] = node(ret[i]) ret[i-1].next = ret[i] return ret[0] import heapq as hq def B(lists): h = [] for i in lists: head = i while head: h.append(head.val) head = head.next hq.heapify(h) return h from LINK import makeLL, printLL a=[1,4,5] b=[1,3,4] c=[2,6] headA=makeLL(a) headB=makeLL(b) headC=makeLL(c) printLL(A([headA,headB,headC]))
# n via recursion WIP def B(head): head = B_helper(head,None) return head def B_helper(node,prev): if node == None: return prev tmp = node nextN = node.next node.next = prev return B_helper(nextN, tmp) # n using prev variable def C(head): prev = None curr = head while curr: tmp = curr.next curr.next = prev prev = curr curr = tmp return prev # because curr is None, and prev is the new head (formerly tail) from LINK import makeLL, printLL a=[1,2,3,4,5,6,7] head=makeLL(a) printLL(A(head))