LeeCode Add Two Numbers问题

问题描述:

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.

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

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
代码:
/**
 * 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) {
		ListNode * L3 = l1;
		ListNode * L4 = l2;
		int L1Len = 0, L2Len = 0;
		while (L3 != NULL || L4 != NULL) {
			if (L3 != NULL) {
				L1Len++;
				L3 = L3->next;
			}
			if (L4 != NULL) {
				L2Len++;
				L4 = L4->next;
			}
		}
		L3 = l1;
		L4 = l2;
		ListNode * temNode = new ListNode(0);
		temNode->val = 0;
		bool tag = false;
		if (L1Len > L2Len) {
			while (L3 != NULL || L4 != NULL) {
				if (tag) {
					L3->val = L3->val + 1;
					tag = false;
				}
				if (L4 != NULL) {
					L3->val = L3->val + L4->val;
					L4 = L4->next;
				}
				else
					L3->val = L3->val;
				if (L3->val >= 10) {
					L3->val = L3->val - 10;
					tag = true;
					if (L3->next == NULL)
						L3->next = temNode;
				}
				L3 = L3->next;
			}
			delete L3;
			delete L4;
			return l1;
		}
		else {
			while (L3 != NULL || L4 != NULL) {
				if (tag) {
					L4->val = L4->val + 1;
					tag = false;
				}
				if (L3 != NULL) {
					L4->val = L4->val + L3->val;
					L3 = L3->next;
				}
				else
					L4->val = L4->val;
				if (L4->val >= 10) {
					L4->val = L4->val - 10;
					tag = true;
                    if(L4->next == NULL)
                        L4->next = temNode;
				}
				L4 = L4->next;
			}
		}
		delete L3;
		delete L4;
		return l2;
	}
};

  结果:

 

posted @ 2019-02-25 11:36  学术不精的霍尔系数  阅读(131)  评论(0编辑  收藏  举报