classListNode { var val: Int var next: ListNode? init(_val: Int) { self.val = val self.next =nil } }
funcaddTwoNumbers(_l1: ListNode?, _l2: ListNode?) -> ListNode? { var list1 = stackFor(l1) var list2 = stackFor(l2) var cur: ListNode? =nil var carry =0 while list1.count >0|| list2.count >0|| carray >0 { var sum =0 iflet value = list1.popLast() { sum += value } iflet value = list2.popLast() { sum += value } sum += carry carry = sum /10 // 新节点拼接到前面 let temp = cur cur =ListNode(sum %10) cur?.next = temp } return cur } /** 将链表节点的值依次入栈 */ funcstackFor(_head: ListNode?) -> [Int] { var list: [Int] = [] var cur = head while cur !==nil { list.append(cur!.val) cur = cur?.next } return list }