俊介三

一天更新一点,一天积累一点

导航

Add two numbers

Posted on 2013-03-11 13:09  俊介三在前进  阅读(163)  评论(0)    收藏  举报

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

http://discuss.leetcode.com/questions/189/add-two-numbers

#include <stdio.h>

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
 
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    ListNode *p1 = l1;
    ListNode *p2 = l2;
    ListNode *tail=NULL;
    ListNode *head=NULL;
    int carry = 0;
    while(p1!=NULL ||p2!=NULL||carry!=0){
        int total = 0;
        if(p1!=NULL){
            total +=p1->val;
            p1 = p1->next;
        }
        if(p2!=NULL){
            total +=p2->val;
            p2 = p2->next;
        }
        if(carry!=0){
            total +=carry;
        }
        carry = total/10;

        if(head==NULL){
            head = new ListNode(total%10);
            tail = head;
        }else{
            tail->next = new ListNode(total%10);
            tail = tail ->next;
        }
    }
    return head;
}

int main(){
    ListNode *n1 = new ListNode(5);
    ListNode *n2 = new ListNode(5);
    ListNode *n3 = addTwoNumbers(n1,n2);
    while(n3!=NULL){
        printf("%d ",n3->val);
        n3 = n3->next;
    }
    return 0;
}

总结:

1.结构体初始化ListNode(int x) : val(x), next(NULL) {}这样写很方便。也竟然不用加个空的Constructor?

2.最初想不明白头部怎么创建,单独创个head出来再循环处理别的,这样有冗余代码。后来用if(head==NULL)就创建head使得整个过程使用一个循环就够了。

3.循环的时候,把当前循环指针设置命名为tail,因为每次循环都在链表的尾部,有助于理解。