LeetCode每日一题:add two numbers

2017-07-06  本文已影响15人  yoshino

问题描述

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

问题分析

这题考查链表基本操作,没什么难度。

代码实现

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode head = new ListNode(0);
        ListNode cur = head;
        int temp = 0;
        while (l1 != null || l2 != null || temp != 0) {
            if (l1 != null) {
                temp = temp + l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                temp = temp + l2.val;
                l2 = l2.next;
            }
            cur.next = new ListNode(temp % 10);
            cur = cur.next;
            temp = temp / 10;
        }
        return head.next;
    }
上一篇 下一篇

猜你喜欢

热点阅读