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

链表相加(二)

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

W:
将需要的两个链表进行反转,便于计算;
叠加后的链表为符合题目要求,需要再次反转
N:
ListNode* cur= new ListNode(val);方式增加新的节点
注意遍历时需要判断是否为空,到下一个也需要判断
如果两个链表都为空,但是还有进位,则需要继续循环

/**
 * 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 *reverseList(ListNode *head) {
        if (head == nullptr || head->next == nullptr) return head;
        ListNode *l = head, *r = l->next;
        l->next = nullptr;
        while (r) {
            ListNode *t = r->next;
            r->next = l;
            l = r;
            r = t;
        }
        return l;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        if(head1==nullptr){
            return head2;
        }
         if(head2==nullptr){
            return head1;
        }
         ListNode* l1= reverseList(head1);
        ListNode* l2= reverseList(head2);
        ListNode* res= new ListNode(0);
        ListNode* cur=res;
        int l=0;
        while(l1 || l2 || l  ){
            //如果两个链表都为空,但是还有进位,则需要继续循环
            int v1= l1? l1->val: 0;//需要判断是否为空节点
            int v2=l2 ? l2->val: 0;

            int sum=(l+v1+v2)%10;
            l=(l+v1+v2)/10;
            cur->next=new ListNode(sum);//避免多出节点
            cur=cur->next;//note 
            if(l1) l1=l1->next;//还是需要判断
            if(l2) l2=l2->next; 

        }
        res=res->next;
        res=reverseList(res);
        return res;


    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-27 15:19
简历上能写3个月吗?
码农索隆:大胆写,主要你能把实习经历包装好,可以看一下我这篇帖子https://www.nowcoder.com/share/jump/4888395581180798063
点赞 评论 收藏
分享
点赞 评论 收藏
分享
头顶尖尖的程序员:我也是面了三四次才放平心态的。准备好自我介绍,不一定要背熟,可以记事本写下来读。全程控制语速,所有问题都先思考几秒,不要急着答,不要打断面试官说话。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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