Adding the number of two endless algorithm (single chain)

We are given two non-empty list is used to represent two non-negative integer. Where their respective bits are stored in reverse order of the way, and they each node can store only one digit.

If we add up these two numbers, it will return a new list and to represent them.

You can assume that in addition to the numbers 0, these two numbers will not begin with 0.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Cause: 342 + 465 = 807

Ideas:

First, a new head node res, as the return value
while simultaneously loop through two-way linked list, even if the head of a linked list continues to loop through, adding the value of their nodes, the list stored in the res
Key:

  1. If greater than 9, to generate the next node linked list res, 初始值为1(carry)
  2. If less than 9, to generate the next node in the list res, initial value 0
  3. If both are empty, does not generate a new tail node

answer:

When execution: 2 ms, beat the 99.96% of all users to submit in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res=new ListNode(0);
        ListNode temp=res;
        while(l1!=null||l2!=null){
            int val1= l1==null?0:l1.val;
            int val2= l2==null?0:l2.val;
            int sum=temp.val+val1+val2;
            if(sum>9){
                sum-=10;
                temp.next=new ListNode(1);
            }
            temp.val=sum;
            l1=l1==null?null:l1.next;
            l2=l2==null?null:l2.next;
            if(temp.next==null){
                temp.next=l1!=null||l2!=null?new ListNode(0):null;
            }
            temp=temp.next;
        }
        return res;
    }
}
Published 125 original articles · won praise 236 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_33709508/article/details/103885729