Add Two Numbers, Leetcode 解题笔记

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

这道题的主要难点有两个:
1. 处理两个list长度不一样的情况。
2. 处理进位的情况。

思路很简单,主要是list node的操作,有几个值得关注的地方:
1. 为了保证原来的list nodes不丢失,可以创建新的nodes来作pointers,此好习惯要保持。
2. 不要忘记处理最后一位时的进位情况,如果最后一位还有进位,需要额外加一个node,幷赋值为1。

代码如下:

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        //create a new node for the result's holder
        ListNode newNode = new ListNode(0);
        
        //create pointers for all lists, so we still have access to the start of each list
        ListNode p1 = l1, p2 = l2, p3 = newNode;
        
        while(p1 != null || p2 != null){
            if(p1 != null){
                carry = carry + p1.val;
                p1 = p1.next;
            }
            if(p2 != null){
                carry = carry + p2.val;
                p2 = p2.next;
            }
            //get the result for current digit, then move pointer to next position
            p3.next = new ListNode(carry%10);
            p3 = p3.next;
            
            //update value of carry
            carry = carry/10;
        }
        
        //for the final digit, if there is a carry, add it to the end of the list
        if(carry == 1)
            p3.next = new ListNode(1);
        
        return newNode.next;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s