1. 首页
  2. 软件开发
  3. day-25 两数相加

day-25 两数相加

  • 发布于 2024-09-26
  • 1 次阅读

思路:因为两个数字是逆序的,所以只需将对应位置的值相加,有进位则进位,再将结果利用头插法存入一个新的链表

注意点:两个链表不一定一样长

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;

    }

}

原文链接: https://blog.csdn.net/qq_53568730/article/details/136921774