题解 | #两个链表生成相加链表#

两个链表生成相加链表

http://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
        stack<int> a,b;
        int a_l=0,b_l=0;
        while(head1)
        {
            a.push(head1->val);
            a_l+=1;
            head1=head1->next;
        }
        while(head2)
        {
            b.push(head2->val);
            b_l+=1;
            head2=head2->next;
        }
        int acc=0;
        vector<int> ans;
        
        while(!a.empty()&&!b.empty()){
            int temp=a.top() + b.top() + acc;
            a.pop();
            b.pop();
            ans.push_back(temp%10);
            acc=temp/10;
            a_l--;
            b_l--;
        }
        cout<<a_l<<" "<<b_l;
        while(!a.empty())
        {    
            int temp=a.top()+acc;
            a.pop();
            ans.push_back(temp%10);
            acc=temp/10;
        }
        while(!b.empty())
        {
            int temp=b.top()+acc;
            b.pop();
            ans.push_back(temp%10);
            acc=temp/10;
        }
        if(acc!=0)
            ans.push_back(acc);
//         cout<<c;
        ListNode* head=new ListNode(-1);
        reverse(ans.begin(),ans.end());
        ListNode* p=head;
        for(int i=0;i<ans.size();i++)
        {
             p->next=new ListNode(ans[i]);
            p=p->next;
        }
        return head->next;
    }
};


全部评论

相关推荐

迟缓的斜杠青年巴比Q了:简历被投过的公司卖出去了,我前两天遇到过更离谱的,打电话来问我有没有意向报班学Java学习,服了,还拿我学校一个学长在他们那报班学了之后干了华为OD当招牌
点赞 评论 收藏
分享
鬼迹人途:你去投一投尚游游戏,服务器一面,第一个图算法,做完了给你一个策略题,你给出方案他就提出低概率问题,答不上当场给你挂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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