LeetCode 445. Add Two Numbers II

来源:互联网 发布:cmd查询数据库 编辑:程序博客网 时间:2024/06/01 07:34

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {       //用两个栈分别存放l1和l2的元素,然后对应相加       Stack<Integer> stack1=new Stack<Integer>();       Stack<Integer> stack2=new Stack<Integer>();       ListNode p=l1,q=l2;       ListNode head=new ListNode(0);       while(p!=null){           stack1.push(p.val);           p=p.next;       }       while(q!=null){           stack2.push(q.val);           q=q.next;       }       //将相同长度部分加起来,进位carry       int carry=0;       int temp_val=stack1.pop()+stack2.pop();       ListNode r=new ListNode(temp_val%10);       if(temp_val>=10)           {               carry=1;           }else{               carry=0;           }       while(!stack1.empty() && !stack2.empty()){           temp_val=stack1.pop()+stack2.pop()+carry;           ListNode temp=new ListNode(temp_val%10);           temp.next=r;           r=temp;           if(temp_val>=10)           {               carry=1;           }else{               carry=0;           }       }       while(!stack1.empty()){           temp_val=stack1.pop()+carry;           ListNode temp=new ListNode(temp_val%10);           temp.next=r;           r=temp;           if(temp_val>=10){               carry=1;           }else{               carry=0;           }       }       while(!stack2.empty()){           temp_val=stack2.pop()+carry;           ListNode temp=new ListNode(temp_val%10);           temp.next=r;           r=temp;           if(temp_val>=10){               carry=1;           }else{               carry=0;           }           }       if(carry>0){           ListNode temp=new ListNode(carry);           temp.next=r;           r=temp;       }       return r;    }}

0 0
原创粉丝点击