0
点赞
收藏
分享

微信扫一扫

牛客热题:链表相加(二)

其生 2024-05-13 阅读 13

在这里插入图片描述

文章目录

牛客热题:链表相加(二)

题目链接

链表相加(二)_牛客题霸_牛客网 (nowcoder.com)

方法一:反转

思路

  • 将两个链表head1和head2都进行反转
  • 然后将两个链表相加的结果存储在另一个链表之中

代码

    ListNode* ReverseList(ListNode* head)
    {
        //空链表直接返回和一个节点的情况
        if(head == nullptr || head->next == nullptr) return head;
         
        ListNode* cur = head;
 
        ListNode* n = cur->next;
 
        ListNode* pre = nullptr;
 
        while(cur != nullptr)
        {
            cur->next = pre;
            pre = cur;
            cur = n;
            if(n != nullptr)
            n = n->next;
        }
 
        return pre;
    }

    ListNode* addInList(ListNode* head1, ListNode* head2) 
    {
        ListNode* sum = new ListNode(0);

        ListNode* h1 = ReverseList(head1);
        ListNode* h2 = ReverseList(head2);
        ListNode* s = sum;
        int v = 0;
        while(h1 != nullptr || h2 != nullptr)
        {
            v /= 10;
            if(h1 != nullptr) v += h1->val, h1 = h1->next;
            if(h2 != nullptr) v += h2->val, h2 = h2->next;
            s->next = new ListNode(v % 10);
            s = s->next;
        }
        v /= 10;
        if(v)
        {
            s->next = new ListNode(v % 10);
            s = s->next;
        }

        sum->next = ReverseList(sum->next);

        return sum->next;
    }

复杂度

举报

相关推荐

0 条评论