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

链表相加(二)

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

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <cstdlib>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        if (head1 == nullptr) {
            return head2;
        }
        if (head2 == nullptr) {
            return head1;
        }
        head1 = Reverse(head1);
        head2 = Reverse(head2);
        ListNode* pHead = new ListNode(0);
        pHead->next = nullptr;
        int carry = 0;
        ListNode* p1, *p2;
        p1 = head1;
        p2 = head2;
        while (p1 != nullptr || p2 != nullptr) {
            int a, b;
            if (p1 == nullptr) {
                a = 0;
            } else {
                a = p1->val;
            }
            if (p2 == nullptr) {
                b = 0;
            } else {
                b = p2->val;
            }
            int sum = (a + b + carry) % 10;
            carry = (a + b + carry) / 10;
            ListNode* s = new ListNode(sum);
            s->next = pHead->next;
            pHead->next = s;
            if (p1 != nullptr) {
                p1 = p1->next;
            }
            if (p2 != nullptr) {
                p2 = p2->next;
            }
        }
        if (carry != 0) {
            ListNode* s = new ListNode(carry);
            s->next = pHead->next;
            pHead->next = s;
        }
        return pHead->next;
    }

    ListNode* Reverse(ListNode* head) {//翻转链表(原本的翻转方法时间复杂度过高)
        if(head==nullptr || head->next==nullptr)
            return head;
        ListNode *a=nullptr, *b=head, *c=head->next;
        while(c!=nullptr) {
            b->next=a;
            a=b;
            b=c;
            c=c->next;
        }
        b->next=a;
        return b;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-27 20:55
点赞 评论 收藏
分享
白火同学:大二有这水平很牛了,可以适当对关键信息加粗一点,比如关键技术、性能指标之类的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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