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

链表相加(二)

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

class Solution {
public:
    /**
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        if(head1==NULL||head2==NULL)
            return (head1==NULL)? head1:head2;

        ListNode* ans = new ListNode(-1);
        ListNode* res = ans;

        reverselist(head1);
        reverselist(head2);

        //cout << head1->val << "|" << head2->val << endl;

        int flag = 0;

        while(head1!=NULL||head2!=NULL||flag==1){
            int tem1 = head1==NULL? 0:head1->val;
            int tem2 = head2==NULL? 0:head2->val;

            //cout << tem1 << "||" << tem2 << endl;


            int tem = tem1+tem2+flag;



            flag = tem/10;
            int anstem = tem%10;


            //cout << tem << "|" << anstem << endl;

            ans->next = new ListNode(anstem);
            ans = ans->next;

            //cout << anstem << endl;

            if(head1!=NULL)
                head1 = head1->next;
            if(head2!=NULL)
                head2 = head2->next;
        }

        reverselist(res->next);
        return res->next;
    }

    void reverselist(ListNode* &head){//? 结构体指针只是值传递,不是地址传递 注意加引用
        //ListNode* pre;  //? 结构体指针变量不能连续定义
        ListNode* cur;
        ListNode* next;

        cur = head->next;
        head->next = NULL;
        next = cur->next;

        while(cur!=NULL){
            cur->next = head;

            head = cur;
            cur = next;
            next = next->next;

        }


    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-04 18:02
好不容易拿到了字节Offer,鼠鼠做后端的,但家里人觉得可能被裁员不稳定,让鼠鼠去投国企,现在好纠结到底该咋选
文档传偷助手:该投就投吧,不过建议别放弃offer 拿到手里的才是最好的
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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