[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.因为存储是反过来的,即数字342存成2->4->3,所以要注意进位是向后的;

2.链表l1或l2为空时,直接返回,这是边界条件,省掉多余的操作;

3.链表l1和l2长度可能不同,因此要注意处理某个链表剩余的高位;

4.2个数相加,可能会产生最高位的进位,因此要注意在完成以上1-3的操作后,判断进位是否为0,不为0则需要增加结点存储最高位的进位。

我的代码如下,欢迎大牛指导交流~

AC,Runtime: 216 ms

//LeetCode_Add Two Numbers
//Written by zhou
//2013.11.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 *resList = NULL, *pNode = NULL, *pNext = NULL;
        ListNode *p = l1, *q = l2;
        int up = 0;
        while(p != NULL && q != NULL)
        {
            pNext = new ListNode(p->val + q->val + up);
            up = pNext->val / 10;    //计算进位
            pNext->val = pNext->val % 10;   //计算该位的数字
            
            if (resList == NULL)  //头结点为空
            {
                resList = pNode = pNext;
            }
            else //头结点不为空
            {
                pNode->next = pNext;
                pNode = pNext;
            }
            p = p->next;
            q = q->next;
        }

		//处理链表l1剩余的高位
		while (p != NULL)
		{
			pNext = new ListNode(p->val + up);
			up = 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 + up);
			up = pNext->val / 10;    
            pNext->val = pNext->val % 10;
			pNode->next = pNext;
            pNode = pNext;
			q = q->next;
		}

		//如果有最高处的进位,需要增加结点存储
		if (up > 0)
		{
			pNext = new ListNode(up);
			pNode->next = pNext;
		}

        return resList;
    }

};

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值