def addTwoNumbers2(self, l1: ListNode, l2: ListNode) -> ListNode: """ Regular solution using a stack. """ def get_stack(l: ListNode) -> List[int]: stack, curr = [], l while curr: stack.append(curr.val) curr = curr.next return stack s1, s2 = get_stack(l1), get_stack(l2) carry, nextNode = 0, None while s1 or s2 or carry: curr = 0 if s1: curr += s1.pop() if s2: curr += s2.pop() carry, curr = divmod(curr + carry, 10) currNode = ListNode(curr) currNode.next = nextNode nextNode = currNode return nextNode
def removeNthFromEnd(self, head: 'ListNode', n: 'int') -> 'ListNode': refDict = {} cnt = 0 fakeHead = ListNode(None) fakeHead.next = head while fakeHead is not None: cnt += 1 refDict[cnt] = fakeHead fakeHead = fakeHead.next # When list is too short, return the original list head directly. if cnt > n: # The node to be deleted is stored at refDict[cnt - n + 1]. refDict[cnt - n].next = refDict.get(cnt - n + 2) return refDict[1].next
def deleteNode(self, node: ListNode): node.val = node.next.val node.next = node.next.next