445. 两数相加 II
Posted xiyangchen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了445. 两数相加 II相关的知识,希望对你有一定的参考价值。
给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) 输出: 7 -> 8 -> 0 -> 7
1 import java.util.Stack; 2 3 public class AddTwoNumbersII { 4 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 5 Stack<ListNode> st1 = new Stack<>(); 6 Stack<ListNode> st2 = new Stack<>(); 7 ListNode temp1 = l1; 8 ListNode temp2 = l2; 9 while(temp1 != null) { 10 st1.push(temp1); 11 temp1 = temp1.next; 12 } 13 while(temp2 != null) { 14 st2.push(temp2); 15 temp2 = temp2.next; 16 } 17 int flag = 0; 18 ListNode res = new ListNode(-1); 19 ListNode result = res.next; 20 while(!st1.empty() && !st2.empty()) { 21 int sum = st1.pop().val + st2.pop().val + flag; 22 flag = 0; 23 if(sum > 9) { 24 sum = sum % 10; 25 flag = 1; 26 } 27 ListNode newHead = new ListNode(sum); 28 newHead.next = result; 29 result = newHead; 30 } 31 while(!st1.empty()) { 32 int sum = st1.pop().val + flag; 33 flag = 0; 34 if(sum > 9) { 35 sum = sum % 10; 36 flag = 1; 37 } 38 ListNode newHead = new ListNode(sum); 39 newHead.next = result; 40 result = newHead; 41 } 42 while(!st2.empty()) { 43 int sum = st2.pop().val + flag; 44 flag = 0; 45 if(sum > 9) { 46 sum = sum % 10; 47 flag = 1; 48 } 49 ListNode newHead = new ListNode(sum); 50 newHead.next = result; 51 result = newHead; 52 } 53 if(flag == 1) { 54 ListNode newHead = new ListNode(1); 55 newHead.next = result; 56 result = newHead; 57 } 58 return result; 59 } 60 61 class ListNode { 62 int val; 63 ListNode next; 64 ListNode(int x) { val = x; } 65 } 66 }
以上是关于445. 两数相加 II的主要内容,如果未能解决你的问题,请参考以下文章