LeetCode 2:Add Two Numbers

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
       ListNode cur1 = l1;
       ListNode cur2 = l2;
       ListNode head = null;
       ListNode cur = null;
       int sum = 0;
       while (cur1 != null || cur2 != null) {
           if (cur1 != null) {
               sum += cur1.val;
               cur1 = cur1.next;
           }
           if (cur2 != null) {
               sum += cur2.val;
               cur2 = cur2.next;
           }
           if (head == null) {
               head = new ListNode(sum % 10);
               cur = head;
           } else {
               cur.next = new ListNode(sum % 10);
               cur = cur.next;
           }
           sum /= 10;
       }
       if (sum == 1)
           cur.next = new ListNode(1);
       return head;
    }
}

 

中间那部分处理head是否为null的情况比较麻烦,可以采用一个 dummy node 简化

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
       ListNode cur1 = l1;
       ListNode cur2 = l2;
       ListNode head = new ListNode(0);
       ListNode cur = head;
       int sum = 0;
       while (cur1 != null || cur2 != null) {
           if (cur1 != null) {
               sum += cur1.val;
               cur1 = cur1.next;
           }
           if (cur2 != null) {
               sum += cur2.val;
               cur2 = cur2.next;
           }
           cur.next = new ListNode(sum % 10);
           cur = cur.next;
           sum /= 10;
       }
       if (sum == 1)
           cur.next = new ListNode(1);
       return head.next;
    }
}

 

 

 

2015-10-15

posted @ 2015-10-15 22:20  whu.yt  阅读(129)  评论(0编辑  收藏  举报