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

链表相加(二)

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <iostream>
#include <ostream>
#include <string>
class Solution {
public:
    ListNode* reverse(ListNode* head){
        ListNode* pre=nullptr;
        ListNode* cur=head;
        while(cur!=nullptr){
            ListNode* temp=cur->next;
            cur->next=pre;
            pre=cur;
            cur=temp;
        }
        return pre;
    }
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        ListNode* cur1=reverse(head1);
        ListNode* cur2=reverse(head2);
        int temp=0;
        ListNode* dummy=new ListNode(0);
        ListNode* head=dummy;
        while(cur1!=nullptr||cur2!=nullptr){
            int x=0;
            int y=0;
            if(cur1!=nullptr)x=cur1->val;
            if(cur2!=nullptr)y=cur2->val;
            int num=x+y+temp;
            temp=num/10;
            head->next=new ListNode(num%10);
            head=head->next;
            if(cur1!=nullptr)cur1=cur1->next;
            if(cur2!=nullptr)cur2=cur2->next;
        }
        if(temp>0){
            head->next=new ListNode(temp);
        }
        
        ListNode* result=reverse(dummy->next);
        return result;

    }
};

反转链表

全部评论

相关推荐

机械打工仔:我来告诉你原因,是因为sobb有在线简历,有些HR为了快会直接先看在线简历,初步感觉不合适就不会找你要详细的了
投了多少份简历才上岸
点赞 评论 收藏
分享
07-15 16:52
已编辑
门头沟学院 Java
周五投的,流程今天结束
投递地平线等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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