LeetCode2: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

一、题目描述

给定两个链表,它们表示两个逆序的非负整数,要求计算它们的和并以同样的方式逆序输出。比如,两个链表(2 -> 4 -> 3)和(5 -> 6 -> 4),即342+465=807,结果逆序输出为:7 -> 0 -> 8

二、解题思路

链表l1或者l2为空时,直接返回;
存储是反过来的,即数字342存成2->4->3,所以要注意进位是向后的;
两个数相加,可能会产生最高位的进位,因此要注意最后判断进位是否为1,为1则需要增加结点存储最高位的进位。

/**
 * 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) {
		// IMPORTANT: Please reset any member data you declared, as
		// the same Solution instance will be reused for each test case.

		if (l1 == NULL) return l2;
		if (l2 == NULL) return l1;

		ListNode *resultList = NULL, *pNode = NULL, *pNext = NULL;
		ListNode *p = l1, *q = l2;
		int ca = 0;
		while (p != NULL && q != NULL)
		{
			pNext = new ListNode(p->val + q->val + ca);
			ca = pNext->val / 10;    //计算进位
			pNext->val = pNext->val % 10;   //计算该位的数字

			if (resultList == NULL)  //头结点为空
			{
				resultList = pNode = pNext;
			}
			else //头结点不为空
			{
				pNode->next = pNext;
				pNode = pNext;
			}
			p = p->next;
			q = q->next;
		}

		//处理链表l1剩余的高位
		while (p != NULL)
		{
			pNext = new ListNode(p->val + ca);
			ca = pNext->val / 10;//计算进位
			pNext->val = pNext->val % 10;//计算该位的数字
			pNode->next = pNext;
			pNode = pNext;
			p = p->next;
		}

		//处理链表l2剩余的高位
		while (q != NULL)
		{
			pNext = new ListNode(q->val + ca);
			ca = pNext->val / 10;
			pNext->val = pNext->val % 10;
			pNode->next = pNext;
			pNode = pNext;
			q = q->next;
		}

		//当两个链表都遍历完成后,如果有最高处的进位(即ca=1),则需要生成一个节点值为1的新节点
		if (ca ==1)
		{
			pNext = new ListNode(1);
			pNode->next = pNext;
		}

		return resultList;
	}

};



LeetCode2:Add Two Numbers_第1张图片

你可能感兴趣的:(LeetCode2:Add Two Numbers)