您的位置:首页 > 编程语言 > Java开发

Java实现-链表求和2

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

您在真实的面试中是否遇到过这个题? 

Yes

样例

给出 
6->1->7
 + 
2->9->5
。即,
617
+ 295

返回 
9->1->2
。即,
912
 。

/**
* Definition for singly-linked list.
* 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
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
Stack<ListNode> stack1=new Stack<ListNode>();
while(l1!=null){
ListNode node=l1;
l1=l1.next;
node.next=null;
stack1.add(node);
}
Stack<ListNode> stack2=new Stack<ListNode>();
while(l2!=null){
ListNode node=l2;
l2=l2.next;
node.next=null;
stack2.add(node);
}
ListNode dummy=new ListNode(-1);
int carry=0;
while(!stack1.isEmpty()&&!stack2.isEmpty()){
ListNode node1=stack1.pop();
ListNode node2=stack2.pop();
int temp=node1.val+node2.val+carry;
ListNode s=new ListNode(temp%10);
if(temp>9){
carry=1;
if(dummy.next==null){
dummy.next=s;
}else{
ListNode node=dummy.next;
s.next=node;
dummy.next=s;
}
}else{
carry=0;
if(dummy.next==null){
dummy.next=s;
}else{
ListNode node=dummy.next;
s.next=node;
dummy.next=s;
}
}
}
if(stack1.isEmpty()){
while(!stack2.isEmpty()){
ListNode node2=stack2.pop();
int temp=carry+node2.val;
ListNode s=new ListNode(temp%10);
if(temp>9){
ListNode node=dummy.next;
s.next=node;
dummy.next=s;
carry=1;
}else{
ListNode node=dummy.next;
s.next=node;
dummy.next=s;
carry=0;
}
}
}
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
ListNode node1=stack1.pop();
int temp=carry+node1.val;
ListNode s=new ListNode(temp%10);
if(temp>9){
ListNode node=dummy.next;
s.next=node;
dummy.next=s;
carry=1;
}else{
ListNode node=dummy.next;
s.next=node;
dummy.next=s;
carry=0;
}
}
}
if(carry==1){
ListNode s=new ListNode(1);
ListNode node=dummy.next;
s.next=node;
dummy.next=s;
return dummy.next;
}else{
return dummy.next;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表求和