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

链表相加(二)

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;

    }
};

反转链表

全部评论

相关推荐

湫湫湫不会java:为啥25届才17,个人信息没打码哦
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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