Interview - Add two number - #2

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

题目比较简单, 主要考察链表操作的熟练程度, 以及各种边界情况的处理, 这种题目, 要一次写对, 不留 bug.

 1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
 2         if (l1 == null) return l2;
 3         if (l2 == null) return l1;
 4         
 5         ListNode head = new ListNode(0);
 6         ListNode curr = head;
 7         boolean isCarry = false;
 8         while (l1 != null || l2 != null) {
 9             int val = (isCarry ? 1 : 0) + (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val);
10             if (val >= 10) {
11                 isCarry = true;
12                 val -= 10;
13             } else {
14                 isCarry = false;
15             }
16             ListNode node = new ListNode(val);
17             curr.next = node;
18             curr = node;
19             l1 = l1 == null ? null : l1.next;
20             l2 = l2 == null ? null : l2.next;
21         }
22         
23         if (isCarry) {
24             ListNode node = new ListNode(1);
25             curr.next = node;
26         }
27         
28         return head.next;
29     }

 

posted on 2016-01-29 15:49  小蒜  阅读(112)  评论(0)    收藏  举报

导航