[LeetCode]Add Two Numbers

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

即 342+465= 807

码了一下,一直是Memory Limited ,才发现是漏了 l2 = l2->next;l1 = l1->next; 囧

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    	if(l2==NULL) return l1;
		if(l1==NULL) return l2;
        ListNode *l3=NULL;
    	ListNode *p = l3;
		int flag=0;
		while( l1!=NULL || l2!=NULL ){
			int sum =  flag;
			if(l1!=NULL){
				sum += l1->val;
				l1 = l1->next;
			}
			if(l2!=NULL){
				sum += l2->val;
				l2 = l2->next;
			}
			int current ;
			flag   = sum /10;
			current= sum%10;
			ListNode *tmp = new ListNode(current);
			
			if(l3==NULL){
			    l3 = tmp;
				p  = l3;
			}else{
				p->next = tmp;
				p = p->next;
			}
		}
		if ( flag != 0){
			ListNode *tmp = new ListNode(flag);
			p->next   = tmp;
		}
		return l3;
    }
};



posted @ 2012-11-05 15:01  程序员杰诺斯  阅读(83)  评论(0编辑  收藏  举报