【LeetCode】2.两数相加 (C++ )& 单链表

创建一个单链表,链表包含一个m_key和一个next指针,一个数据可以通过next指针指向下一个数据,不停的next。

#include <iostream>
using namespace std;

struct ListNode{
    int m_key;
    ListNode* next;
    ListNode(int x): m_key(x), next(nullptr){} // 构造函数
};

void createList(ListNode* pHead){
    ListNode* p = pHead;
    for(int i=1;i<10;++i){
        ListNode* pNewNode = new ListNode(0);
        pNewNode->m_key = i;
        pNewNode->next = nullptr;//需要先赋值
        p->next = pNewNode;
        p=pNewNode;
    }
}

int main() {
    ListNode* head = new ListNode(0); //初始化链表
    head->m_key = 0;
    head->next = nullptr;
    createList(head);
    cout<<head->next->next->m_key<<endl;
    return 0;
}

来个实战转载自:https://blog.csdn.net/qq_32805671/article/details/79883391

题目地址:https://leetcode-cn.com/problems/add-two-numbers/description/

问题描述:

给定两个非空链表来代表两个非负整数,位数按照逆序方式存储,它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因: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 *result = new ListNode(0);
        ListNode *tmp = result;
        int sum = 0;
        while(l1 || l2){      
            if(l1){
                sum += l1->val;
                l1 = l1->next;
            }
            if(l2){
                sum += l2->val;
                l2 = l2->next;
            }
            tmp->next = new ListNode(sum%10);
            sum /= 10;
            tmp = tmp->next;
        }
        if(sum)
            tmp->next = new ListNode(1);
        return result->next;
    }
};

猜你喜欢

转载自blog.csdn.net/z13653662052/article/details/88251349