【LeetCode445】 Add Two Numbers II★★
题目描述:
解题思路:
给定两个链表(代表两个非负数),数字的各位以正序存储,将两个代表数字的链表想加获得一个新的链表(代表两数之和)。
如(7->2->4->3)(7243) + (5->6->4)(564) = (7->8->0->7)(7807)
此题与【LeetCode2】Add Two Numbers解决思路类似,不同之处在于此题的数字以正序存储,故需要借助栈。
Java代码:
1 import java.util.Stack; 2 //public class LeetCode445为测试代码 3 public class LeetCode445 { 4 public static void main(String[] args) { 5 ListNode l1=new ListNode(7),l11=new ListNode(2),l12=new ListNode(4),l13=new ListNode(3); 6 l1.next=l11; 7 l11.next=l12; 8 l12.next=l13; 9 System.out.print("Input:["+l1.val+","+l11.val+","+l12.val+","+l13.val+"]"); 10 ListNode l2=new ListNode(5),l21=new ListNode(6),l22=new ListNode(4); 11 l2.next=l21; 12 l21.next=l22; 13 System.out.println(",["+l2.val+","+l21.val+","+l22.val+"]"); 14 ListNode list=new Solution().addTwoNumbers(l1, l2); 15 if(list!=null) 16 System.out.print("output:["+list.val); 17 while(list.next!=null){ 18 System.out.print(","+list.next.val); 19 list.next=list.next.next; 20 } 21 System.out.println("]"); 22 } 23 } 24 class Solution { 25 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 26 Stack<Integer> stack1=new Stack<Integer>(); 27 Stack<Integer> stack2=new Stack<Integer>(); 28 while(l1!=null){ 29 stack1.push(l1.val); 30 l1=l1.next; 31 } 32 while(l2!=null){ 33 stack2.push(l2.val); 34 l2=l2.next; 35 } 36 int carry=0; 37 ListNode resultList=new ListNode(0); 38 while(!stack1.empty()||!stack2.empty()){ 39 int sum=carry; 40 if(!stack1.empty()) sum+=stack1.pop(); 41 if(!stack2.empty()) sum+=stack2.pop(); 42 resultList.val=sum%10; 43 ListNode newHead=new ListNode(sum/10); 44 newHead.next=resultList; 45 resultList=newHead; 46 carry=sum/10; 47 } 48 return resultList.val==0?resultList.next:resultList; 49 } 50 } 51 class ListNode { 52 int val; 53 ListNode next; 54 ListNode(int x) { val = x; } 55 }
程序结果: