Add Two Numbers

2017-09-05  本文已影响0人  瞬铭

题目链接:https://leetcode.com/problems/add-two-numbers/description/
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

思路:

遍历两个链表,每位数字累加(同时需要加上结果链表该节点的值),模10为结果为结果列表当前指针值,模10为结果链表next指针初始值。

注意事项:

1.结束条件,除10只要大于0,next指针就需要新建。而不是l1,l2遍历完了,就不新建next指针了

if(key > 0){
    curr.next = new ListNode(key);
}

不是

if(p != null && q != null){
    curr.next = new ListNode(key);
}

2.两个链表长度不相等的情况,遍历l1,l2的结束条件是 “或”

examples:
l1=[1,2];
l2=[3];

java代码

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p = l1;
        ListNode q = l2;
        ListNode l3 = new ListNode(0);
        ListNode curr = l3;
        int key = 0;
        while (p != null || q != null) {
            int pV = (p != null) ? p.val : 0;
            int qV = (q != null) ? q.val : 0;
            int tmp = pV + qV + key;
            key = tmp / 10;
            int mo = tmp % 10;
            curr.next = new ListNode(mo);
            curr = curr.next;
            p = (p != null) ? p.next : p;
            q = (q != null) ? q.next : q;
            if(key > 0){
                curr.next = new ListNode(key);
            }
        }
        return l3.next;
    }

 class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }
 }
上一篇下一篇

猜你喜欢

热点阅读