链表求和II

假定用一个链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字顺序排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。
样例
给出 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; 
  	   }
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值