您的位置:首页 > 其它

链表求和II

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

样例

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

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

import java.util.Scanner;
import java.util.Stack;

/**
* 假定用一个链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字顺序排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。
样例
给出 6->1->7 + 2->9->5。即,617 + 295。

返回 9->1->2。即,912 。
*
* @author Dell
*
*/
public class Test221 {
public static ListNode addLists2(ListNode l1,ListNode l2)
{
if(l1==null)
return l2;
if(l2==null)
return l1;
Stack<Integer> s1=new Stack<>();
Stack<Integer> s2=new Stack<>();
Stack<Integer> s3=new Stack<>();
ListNode result=new ListNode(-1);
ListNode p=l1;
ListNode q=l2;
ListNode r=result;
while(p!=null)
{
s1.push(p.val);
p=p.next;
}
while(q!=null)
{
s2.push(q.val);
q=q.next;
}
int c=0;
while(s1.isEmpty()!=true&&s2.isEmpty()!=true)
{
int a=s1.pop();
int b=s2.pop();
int d=a+b;
if(c==1)
{
d++;
c=0;
}
if(d>=10)
{
d=d-10;
c=1;
}
s3.push(d);
}
while(s1.isEmpty()!=true)
{
int a=s1.pop();
if(c==1)
{
a++;
c=0;
}
if(a>=10)
{
a=a-10;
c=1;
}
s3.push(a);
}
while(s2.isEmpty()!=true)
{
int a=s2.pop();
if(c==1)
{
a++;
c=0;
}
if(a>=10)
{
a=a-10;
c=1;
}
s3.push(a);
}
if(c==1)
{
s3.push(1);
}
while(s3.isEmpty()!=true){
ListNode temp=new ListNode(s3.pop());
r.next=temp;
r=r.next;
}
return result.next;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n1=sc.nextInt();
int n2=sc.nextInt();
ListNode list1=new ListNode(-1);
ListNode p=list1;
for(int i=0;i<n1;i++)
{
ListNode temp=new ListNode(sc.nextInt());
p.next=temp;
p=p.next;
}
ListNode list2=new ListNode(-1);
ListNode q=list2;
for(int i=0;i<n2;i++)
{
ListNode temp=new ListNode(sc.nextInt());
q.next=temp;
q=q.next;
}
ListNode result=addLists2(list1.next,list2.next);
while(result!=null)
{
System.out.print(result.val);
result=result.next;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode