题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

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

class Solution {
public:
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        head1=reverseList(head1);
        head2=reverseList(head2);
        vector<int> sum;
        int t=0;
        while(head1||head2)
        {
            if(head1) t+=head1->val,head1=head1->next;
            if(head2) t+=head2->val,head2=head2->next;
            sum.emplace_back(t%10);
            t=t/10;
//             cout<<t<<endl;
        }
        if(t) sum.emplace_back(1);
        int n=sum.size();
        ListNode* dummy=new ListNode(-1);
        ListNode* current=dummy;
        for(int i=n-1;i>=0;i--)
        {
            ListNode* node=new ListNode(sum[i]);
            current->next=node;
            current=current->next;
        }
        return dummy->next;
    }
    ListNode* reverseList(ListNode* head)
    {
        ListNode* current=head;
        ListNode* prev=nullptr;
        while(current)
        {
            ListNode* tmp=current->next;
            current->next=prev;
            prev=current;
            current=tmp;
        }
        return prev;
    }
};
用了一个链表反转和大数加和。

全部评论

相关推荐

野猪不是猪🐗:我assume that你must技术aspect是solid的,temperament也挺good的,however面试不太serious,generally会feel style上不够sharp
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-19 14:35
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务