Leetcode Add Two Numbers 链表 大数加和模拟 (特别注意链表的指针操作)

传送门

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    string ListNumber(ListNode* list)
    {
        string solve;
        solve.clear();
        while(list!=nullptr)
        {
            solve+=list->val+'0';
            list = list->next;
        }
        return solve;
    }
    string AddTwoString(string l1,string l2)
    {
        string solve;
        solve.clear();
        int len1 = l1.size(),len2 = l2.size();
        int m = max(len1,len2);
        while(len1<m) {
            l1+='0';
            len1++;
        }
        while(len2<m) {
            l2+='0';
            len2++;
        }
        l1+='0',l2+='0';
        int last = 0;
        for(int i = 0;i<m+1;i++)
        {
            int a = l1[i]-'0',b = l2[i]-'0';
            if(a+b+last>=10) {
                solve+=(a+b+last-10+'0');
                last = 1;
            }
            else {
                solve+=(a+b+last+'0');
                last = 0;
            }
        }
        if(solve[m]=='0') solve.erase(m,1);
        return solve;
    }
    void construct(ListNode** pHead,string l3)
    {
        int pos = 0;
        ListNode* now = new ListNode(0);
        now->val = l3[pos]-'0';
        now->next = nullptr;
        (*pHead)->val = now->val;
        (*pHead)->next = nullptr;
        pos++;
        ListNode* pre = *pHead;
        while(pos<l3.size())
        {
            ListNode* now1 = new ListNode(l3[pos]-'0');
            now1->val = l3[pos]-'0';
            now1->next = nullptr;
            pre->next = now1;
            pre = now1;
            pos++;
        }
    }
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        //链表操作
        ListNode* l3 = new ListNode(-1);
        string numl1 = ListNumber(l1);
        string numl2 = ListNumber(l2);
        string numl3 = AddTwoString(numl1,numl2);
        //制作链表
        construct(&l3,numl3);
       // cout<<l3->val<<endl;
        return l3;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值