leedcode 2. Add Two Numbers

本文介绍了一个经典的链表操作问题——两个非空链表表示的非负整数相加,并返回结果链表。提供了C++代码实现及注意事项。

题目描述
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.

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

题目的意思就是将两个数相加,而这两个数的每一位是存在链表的每一个元素中的,从低位到高位。因此,思路是从链表的头部开始,遍历两个链表,注意要分别处理进位以及这一位的结果。另外还要注意链表的长度不一致的情况。
以下是c++实现的代码:

/**
 * 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* p1 = l1;
        ListNode* p2 = l2;
        int plus = 0;
        int value1 = 0;
        int value2 = 0;


        ListNode* result=NULL;
        ListNode* temp = new ListNode(0);
        //只要两个链表有一个不为空,就要继续遍历
        while ((p1 != NULL||p2 != NULL)) {
            if (p1 != NULL) {
                value1 = p1->val;
                p1 = p1->next;
            }
            else {
                value1 = 0;
            }

            if (p2 != NULL) {
                value2 = p2->val;
                p2 = p2->next;
            }
            else {
                value2 = 0;
            }
                    temp->next=new ListNode( (value1 + value2 + plus) % 10);
                    if (result == NULL) {
                        result = temp->next;
                    }
                    temp = temp->next;
                    //进位
            plus = (value1 + value2 + plus) / 10;

        }
        //处理最后的进位
        if (plus != 0) {
            temp->next = new ListNode(plus);
        }
        return result;

    }
};

写出来之后发现也没什么难的。但是几个月没怎么打代码,还是会生疏很多的。希望有意识的加强自己的编程能力。

实现过程中遇到的一个坑就是没有熟悉链表的建立过程。以下的代码,可能一下子看不出什么异常,实际上这样链表从第一个元素开始就没有链接起来。head只能得到只有第一个元素的链表。

int main() {
    ListNode *temp = NULL;
    ListNode *head = NULL;
    int n = 3;
    while (n--) {
        temp = new ListNode(2);

        if (head == NULL) {
        //注意这里因为temp->next==NULL,所以head->next==NULL,和后面的链表断开了
            head = temp;
        }
        //赋值后,temp==NULL,
        temp = temp->next;
    }

    while (head != NULL) {
        cout << head->val << endl;
        head = head->next;
    }
    system("pause");
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值