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

链表相加(二)

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

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */

/*
链表实现的超过int位的算法,有实际价值
*/
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    ListNode* ReverseList(ListNode* head) {
        // write code here
        if (head == nullptr || head->next == nullptr) return head;
        ListNode dummy = ListNode(-1);
        dummy.next = head;
        ListNode* pre = &dummy;
        ListNode* cur = head;
        ListNode* tmp;

        while (cur != nullptr) {
            // cout << cur->val << endl;
            tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        head->next = nullptr;
        return pre;
    }

    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        ListNode *cur1 = ReverseList(head1);
        ListNode *cur2 = ReverseList(head2);

        // ListNode *dummy = new ListNode(-1);
        ListNode *cur = nullptr;
        int tmp;
        int carry = 0;

        while (cur1 != nullptr && cur2 != nullptr) {
            tmp = cur1->val + cur2->val + carry;
            carry = 0;
            if(tmp>=10) carry = 1;
            ListNode* newNode = new ListNode(tmp%10);
            newNode->next = cur;
            cur = newNode;

            cur1 = cur1->next;
            cur2 = cur2->next;
        }
        while(cur1!=nullptr){
            tmp = cur1->val + carry;
            carry = 0;
            if(tmp>=10) carry = 1;
            cout<<tmp<<endl;
            ListNode* newNode = new ListNode(tmp%10);
            newNode->next = cur;
            cur = newNode;

            cur1 = cur1->next;
        }
        while(cur2!=nullptr){
            tmp = cur2->val + carry;
            carry = 0;
            if(tmp>=10) carry = 1;
            ListNode* newNode = new ListNode(tmp%10);
            newNode->next = cur;
            cur = newNode;

            cur2 = cur2->next;
        }
        if(carry==1){
            ListNode* newNode = new ListNode(1);
            newNode->next = cur;
            cur = newNode;
        }
        return cur;
    }
};

用C++又解了一遍这个题目,思路更清晰了。

全部评论
看排行榜里的榜一用的是异步编程的写法,速度是这里的六倍多,看来还有很长的路要走
点赞
送花
回复
分享
发布于 2023-10-02 22:18 广西

相关推荐

头像
不愿透露姓名的神秘牛友
04-08 00:50
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务