Java实现-链表求和2

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

样例

给出 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;
		}
    }  
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Narasimha_Karumanchi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值