/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { Stack<ListNode> Q1 = new Stack<ListNode>(); Stack<ListNode> Q2 = new Stack<ListNode>(); while (l1 != null) { Q1.Push(l1); l1 = l1.next; } while (l2 != null) { Q2.Push(l2); l2 = l2.next; } var list = new List<ListNode>(); var step = 0; while (Q1.Count > 0 || Q2.Count > 0) { var node1 = new ListNode(0); if (Q1.Count > 0) { node1 = Q1.Pop(); } var node2 = new ListNode(0); if (Q2.Count > 0) { node2 = Q2.Pop(); } var x = node1.val + node2.val + step; if (x > 9) { step = 1; } else { step = 0; } var node = new ListNode(x % 10); list.Add(node); } if (step == 1) { list.Add(new ListNode(1)); } list.Reverse(); var head = list[0]; var temp = head; for (int i = 1; i < list.Count; i++) { temp.next = list[i]; temp = list[i]; } return head; } }
https://leetcode.com/problems/add-two-numbers-ii/#/description
补充一个python的实现:
1 class Solution: 2 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 3 stack1 = self.buildStack(l1) 4 stack2 = self.buildStack(l2) 5 head = ListNode(-1) 6 carry = 0 7 while len(stack1) > 0 or len(stack2) > 0 or carry != 0: 8 x = 0 if len(stack1) == 0 else stack1.pop(-1) 9 y = 0 if len(stack2) == 0 else stack2.pop(-1) 10 temp = x + y + carry 11 carry = 0 if temp <= 9 else 1 12 temp = temp % 10 13 node = ListNode(temp) 14 node.next = head.next 15 head.next = node 16 return head.next 17 18 def buildStack(self,node): 19 stack = [] 20 while node != None: 21 stack.append(node.val) 22 node = node.next 23 return stack