Add Two Numbers

Problem

You are given two non-empty linked lists representing two non-negative integers. 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.node

You may assume the two numbers do not contain any leading zero, except the number 0 itself.git

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8code

解題思路

就是按照咱們小時候的豎式加法的方式來計算就能夠了。不一樣的是,這裏的進位是向右進位;而咱們小時候計算加法的進位是向左進位。it

My Solution

class Solution
{
public:
	ListNode* addTwoNumbers(ListNode *l1, ListNode *l2)
	{
		ListNode* p = l1;
		ListNode* q = l2;
		int sum = 0;
		ListNode* sentinel = new ListNode(0);
		ListNode* d = sentinel;
		if ((p == NULL) && (q != NULL))
		{
			return q;
		}
		if ((p != NULL) && (q == NULL))
		{
			return p;
		}
		do
		{
			if (p != NULL)
			{
				sum += (p->val);
				p = p->next;
			}
			else
            {
				sum += 0;
               // p = p->next;
			}

			if (q != NULL)
			{
				sum += (q->val);
				q = q->next;
			}
			else
			{
				sum += 0;
              //  q = q->next;
			}
			d->next = new ListNode((sum % 10));
            d = d->next;
			sum = (sum/10);
            if(q==NULL && q==NULL && sum!=0)
            {
                d->next=new ListNode(sum);
            }
		}while (p != NULL || q != NULL);
		return sentinel->next;
	}

};
相關文章
相關標籤/搜索