class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ currHeap = [] head, l = None, None for li in lists: if li is not None: heappush(currHeap, (li.val, li)) while currHeap: val, node = heappop(currHeap) newNode = ListNode(val) if node.next is not None: heappush(currHeap, (node.next.val, node.next)) if not head: head, l = newNode, newNode else: l.next = newNode l = l.next return head if __name__ == '__main__': sol = Solution() l1 = get_list([1, 2, 3]) l2 = get_list([4, 5]) l3 = get_list([]) lists = [l1, l2, l3] result = sol.mergeKLists(lists) print(result)
remove.counter = -1 else: remove(head, st.next, n) remove.counter += 1 if remove.counter == n - 1: remove.nextNode = st if remove.counter == n + 1: st.next = remove.nextNode if st == head and remove.counter == n: return False return True class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ st = head if not remove(head, st, n): return head.next else: return head if __name__ == '__main__': data = [2, 3, 4, 5] head = get_list(data) sol = Solution() result = sol.removeNthFromEnd(head, 4) print(result)
""" :type l1: ListNode :type l2: ListNode :rtype: ListNode """ val, addition = 0, 0 l, head = None, None while l1 is not None or l2 is not None or addition: v1 = l1.val if l1 is not None else 0 v2 = l2.val if l2 is not None else 0 val = v1 + v2 + addition addition = val // 10 if l is None: l = ListNode(val % 10) head = l else: l.next = ListNode(val % 10) l = l.next l1 = l1.next if l1 is not None else None l2 = l2.next if l2 is not None else None return head if __name__ == '__main__': l1 = get_list([4, 3, 2]) l2 = get_list([9, 1]) sol = Solution() head = sol.addTwoNumbers(l1, l2) while head is not None: print(head.val) head = head.next
def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None: return head st1 = head st2 = head.next previousNode = None while st1 is not None and st2 is not None: if previousNode is None: st1.next = st2.next st2.next = st1 head = st2 else: st1.next = st2.next st2.next = st1 previousNode.next = st2 previousNode = st1 st1 = st1.next st2 = st1.next if st1 is not None else None return head if __name__ == "__main__": sol = Solution() l = get_list([1, 3, 2, 1]) result = sol.swapPairs(l) print(result)