leetcode 445两数相加 ii

445. 两数相加 II

题目描述

解法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<ListNode> s1=new Stack<>();
Stack<ListNode> s2=new Stack<>();
Stack<ListNode> result=new Stack<>();
//入栈
while(l1!=null)
{
s1.push(l1);
l1=l1.next;
}
while(l2!=null)
{
s2.push(l2);
l2=l2.next;
}
int carried = 0;
while(!s1.isEmpty()||!s2.isEmpty())
{
int sum=carried;//进位,初始化
if(!s1.empty())
{
sum+=s1.pop().val;
}
if(!s2.empty())
{
sum+=s2.pop().val;
}
carried=sum/10;
sum%=10;
result.push(new ListNode(sum));
}
//需要进位
if(carried!=0)
{
result.push(new ListNode(carried));
}
ListNode node = new ListNode(-1);
ListNode dummpy = node;
while(!result.isEmpty())
{
node.next=result.pop();
node = node.next;
}
return dummpy.next;
}
}