LeetCode2.2.1(Add Two Numbers)


You are given two linked lists representing two non-negative numbers. e digits are stored in reverse
order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

这道题思路不难,但是要注意进位的问题,同时要注意一开始给出的数据是反序的,代码如下

public static void solution_2_2_1(Node head1,Node head2){
		Node t=null;
		Node p1=head1;
		Node p2=head2;
		int flag=0;
		int data1;
		int data2;
		while(p1!=null||p2!=null){
			if(p1!=null){
				data1=p1.data;
			}
			else{
				data1=0;
			}
			if(p2!=null){
				data2=p2.data;
			}
			else{
				data2=0;
			}
			int data=data1+data2+flag;
			if (data>=10){
				data-=data;
				flag=1;
			}
			else{
				flag=0;
			}
			Node node=new Node(data,t);
			t=node;
			if(p1!=null){
				p1=p1.next;
			}
			if(p2!=null){
				p2=p2.next;
			}
		}
		while(t!=null){
			System.out.print(t.data);
			t=t.next;
		}
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值