[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

注意点:改了又改,好多测试用例没有考虑到。代码很乱~

      1.{5},{5}->{0,1}

      2.{1},{9,9}->{0,0,1}

      3.{9,8},{1}->{0,9}

class Solution {
public:
	int Length(ListNode *l)
	{
		int len=0;
		while(l)
		{
			l=l->next;
			len++;
		}
		return len;
	}
	ListNode *func(ListNode *l1,ListNode *l2)
	{
		ListNode *p=l1;
		ListNode *q=l2;
		ListNode *r=p;
		bool flag=false;
		while(q)
		{
			r=p;
			if(flag)
			{
				p->val+=q->val+1;
				flag=false;
			}
			else
				p->val+=q->val;
			if(p->val>9)
			{
				flag=true;
				p->val=p->val%10;
			}
			p=p->next;
			q=q->next;
		}
		while(flag)
		{
			if(!p)
			{
				ListNode *newnode=new ListNode(1);
				r->next=newnode;
				flag=false;
			}
			else
			{
				p->val+=1;
				flag=false;
				if(p->val>9)
				{
					flag=true;
					p->val=p->val%10;
					r=p;
					p=p->next;
				}
			}
		}
		return l1;
	}
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
		int len1=Length(l1);
		int len2=Length(l2);
		if(len1==0) return l2;
		else if (len2==0) return l1;
		else if(len1<len2) return func(l2,l1);
		else return func(l1,l2);
    }
};

  

 

posted @ 2013-11-06 11:55  七年之后  阅读(244)  评论(0编辑  收藏  举报