Add Two Numbers II

来源:互联网 发布:如何看自己淘宝等级 编辑:程序博客网 时间:2024/04/29 19:39

原题地址:点我传送

比之前的Add Two Numbers I更进一步,这次链表给的是直接按最高位到最低位的顺序,稍微加大了些难度,但是想到类似的结构应该是栈,将两个链表分别存进栈里后再取出来相加,答案再入栈,最后再从答案栈中构建链表,即满足题目要求。

Java:

/** * 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) {        Stack <Integer> L1= new Stack<Integer>(),L2= new Stack<Integer>(),ans= new Stack<Integer>();        while(l1!=null)        {            L1.push(l1.val);            l1=l1.next;        }        while(l2!=null)        {            L2.push(l2.val);            l2=l2.next;        }        int carry = 0;        while(!L1.empty()&&!L2.empty())        {            int n = (L1.peek() + L2.peek() + carry)%10;            carry = (L1.peek() + L2.peek() + carry)/10;            ans.push(n);            L1.pop();            L2.pop();        }        if(L1.empty())        {            while(!L2.empty())            {                int n = (L2.peek() + carry)%10;                carry = (L2.peek() + carry)/10;                ans.push(n);                L2.pop();            }        }        else if(L2.empty())        {            while(!L1.empty())            {                int n = (L1.peek() + carry)%10;                carry = (L1.peek() + carry)/10;                ans.push(n);                L1.pop();            }        }        if(carry!=0)ans.push(carry);        ListNode l3 = new ListNode(ans.peek());        ListNode answer = l3;        ans.pop();        while(!ans.empty())        {            l3.next = new ListNode(ans.peek());            l3=l3.next;            ans.pop();        }        return answer;    }}


0 0
原创粉丝点击