LeetCode之Add Two Numbers

LeetCode之Add Two Numbers

题目: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

Subscribe to see which companies asked this question

中文翻译:

给你两个表示两个非负数字的链表。数字以相反的顺序存储,其节点包含单个数字。将这两个数字相加并将其作为一个链表返回。

输入: (2 -> 4 -> 3) + (5 -> 6 -> 4)输出: 7 -> 0 -> 8


java实现:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
         if(l1==null){
             return l2;
         }
         if(l2==null){
             return l1;
         }
         int sum=0;
         ListNode listNode=new ListNode(0);//这个地方最好新建一个节点,然后用p3代替
         ListNode p1=l1,p2=l2,p3=listNode;
         while(p1!=null||p2!=null){
             if(p1!=null){
                 sum+=p1.val;
                 p1=p1.next;
             }
             if(p2!=null){
                 sum+=p2.val;
                 p2=p2.next;
             }
             p3.next=new ListNode(sum%10);
             p3=p3.next;
             sum/=10;
         }
         if(sum==1)
             p3.next=new ListNode(1);//2个链表长度相等的话,如果加起来超过10,记得增加一个节点
         return listNode.next;  
    }
}

总结:第一反应是要知道循环条件,然后最后要记得有最后有可能会新增加一个节点。


你可能感兴趣的:(LeetCode,arithmetic)