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