思路:因为两个数字是逆序的,所以只需将对应位置的值相加,有进位则进位,再将结果利用头插法存入一个新的链表
注意点:两个链表不一定一样长
code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head=new ListNode(-1);
ListNode thead=head;
int add=0;
while(l1!=null&&l2!=null){
ListNode t=new ListNode();
t.val=(l1.val+l2.val+add)%10;
add=(l1.val+l2.val+add)/10;
thead.next=t;
thead=thead.next;
l1=l1.next;
l2=l2.next;
}
while(l1!=null){
ListNode t=new ListNode();
t.val=(l1.val+add)%10;
add=(l1.val+add)/10;
thead.next=t;
thead=thead.next;
l1=l1.next;
}
while(l2!=null){
ListNode t=new ListNode();
t.val=(l2.val+add)%10;
add=(l2.val+add)/10;
thead.next=t;
thead=thead.next;
l2=l2.next;
}
if(add!=0){
ListNode t=new ListNode();
t.val=add;
thead.next=t;
thead=thead.next;
}
return head.next;
}
}