221. 链表求和 II

假定用一个链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字顺序排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。

样例

样例 1:

输入t:6->1->7   2->9->5
输出 :9->1->2

样例 2:

输入:1->2->3   4->5->6
输出 :6->7->9

/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/

public class Solution {
/**
* @param l1: The first list.
* @param l2: The second list.
* @return: the sum list of l1 and l2.
*/
public ListNode addLists2(ListNode l1, ListNode l2) {
// write your code here
ListNode result=new ListNode(0);
ListNode node=result;
Stack<Integer> s1=new Stack<>();
Stack<Integer> s2=new Stack<>();
int flag=0;
while(l1!=null){
s1.push(l1.val);
l1=l1.next;
}
while(l2!=null){
s2.push(l2.val);
l2=l2.next;
}
while(!s1.isEmpty()||!s2.isEmpty()){
int cursum=0;
if(!s1.isEmpty()&&!s2.isEmpty()){
cursum=s1.peek()+s2.peek()+flag;
}else if (!s1.isEmpty()){
cursum=s1.peek()+flag;
}else{
cursum=s2.peek()+flag;
}
ListNode newList=new ListNode(cursum%10);
newList.next=node.next;
node.next=newList;
flag=cursum/10;
if(!s1.isEmpty()){
s1.pop();
}
if(!s2.isEmpty()){
s2.pop();
}
}
if(flag==1){
ListNode newList=new ListNode(flag);
newList.next=node.next;
node.next=newList;
}
return result.next;
}


}

 

猜你喜欢

转载自www.cnblogs.com/lilanzhou/p/10710407.html