果果1020

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

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.

 1 public class Solution {
 2     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
 3         
 4         ListNode r = new ListNode(0); // dummy node
 5         ListNode t = r;
 6         int carrying = 0;
 7         
 8         while (l1 != null || l2 != null || carrying != 0) {
 9             t.next = new ListNode(carrying);
10             if (l1 != null) {
11                 t.next.val += l1.val;
12                 l1 = l1.next;
13             }
14             if (l2 != null) {
15                 t.next.val += l2.val;
16                 l2 = l2.next;
17             }
18             if (t.next.val >= 10) {
19                 t.next.val -= 10;
20                 carrying = 1;
21             } else {
22                 carrying = 0;
23             }
24             t = t.next;
25         }
26         
27         return r.next;
28     }
29 }

 

posted on 2017-01-02 12:17  果果1020  阅读(93)  评论(0)    收藏  举报