public class ListNode {
int val;
ListNode next;
ListNode(int x){
val=x;
}
}
class solution{
public static ListNode addTwoNumbers(ListNode l1,ListNode l2){
ListNode dummyHead=new ListNode(0);
ListNode p=l1;
ListNode q=l2;
ListNode curr=dummyHead;
int carry=0;
while(p!=null||q!=null){
int x=(p!=null)?p.val:0;
int y=(q!=null)?q.val:0;
int sum=carry+x+y;
carry=sum/10;
curr.next=new ListNode(sum%10);
curr=curr.next;
if(p!=null) p=p.next;
if(q!=null) q=q.next;
}
if(carry>0){
curr.next=new ListNode(carry);
}
return dummyHead.next;
}
public static void display(ListNode head) {
for(ListNode cur=head;cur!=null;cur=cur.next) {
System.out.printf("(%d)->",cur.val);
}
System.out.printf("null");
System.out.printf("%n");
}
public static ListNode pushFront(ListNode head,int val) {
ListNode newnode=new ListNode(val);
newnode.next=head;
return newnode;
}
public static void main(String[] args) {
ListNode head=null;
head=pushFront(head,1);
head=pushFront(head,2);
head=pushFront(head,3);
display(head);
ListNode head1=null;
head1=pushFront(head1,4);
head1=pushFront(head1,5);
head1=pushFront(head1,6);
display(head1);
ListNode head3=null;
head3=addTwoNumbers(head1,head);
display(head3);
}
}
[Java]链表面试题计算两数之和
最新推荐文章于 2021-12-20 15:16:23 发布