您的位置:首页 > 其它

两个链表相加

2017-04-04 19:50 232 查看
You are given two linked lists representing two non-negative numbers. The 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

package 训练;
import java.util.*;

public class 两个链表相加1 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
String[] a=sc.nextLine().split(" ");
String[] b=sc.nextLine().split(" ");
ListNode ahead=createListNode(a);
ListNode bhead=createListNode(b);
ListNode chead=addTwoNumbers(ahead,bhead);
ListNode res=chead;
while(res!=null){
System.out.print(res.val+" ");
res=res.next;
}
System.out.println();
}

}

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

int sum=l1.val+l2.val;
int j=sum/10;
ListNode head=new ListNode(sum%10);
ListNode node=head;
l1=l1.next;
l2=l2.next;
while(l1!=null&&l2!=null){
sum=l1.val+l2.val+j;
j=sum/10;
node.next=new ListNode(sum%10);
node=node.next;

l1=l1.next;
l2=l2.next;
}
while(l1!=null){
sum=l1.val+j;
j=sum/10;
node.next=new ListNode(sum%10);
node=node.next;
l1=l1.next;

}
while(l2!=null){
sum=l2.val+j;
j=sum/10;
node.next=new ListNode(sum%10);
node=node.next;
l2=l2.next;

}
if(j>0)
node.next=new ListNode(j);
return head;
}

static ListNode createListNode(String[] a){
ListNode head=new ListNode(Integer.parseInt(a[0]));
ListNode node=head;
for(int i=1;i<a.length;i++){
node.next=new ListNode(Integer.parseInt(a[i]));
node=node.next;
}
return head;
}

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