题解 | 链表相加(二)

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <cstdio>
class Solution {
  public:
    ListNode* reversalList(ListNode* p1) {
        if (p1 == nullptr || p1->next == nullptr) {
            return p1;
        }
        ListNode* tempPtr = p1->next;
        p1->next = nullptr;
        while (tempPtr) {
            ListNode* thirdPtr = tempPtr->next;
            tempPtr->next = p1;
            p1 = tempPtr;
            tempPtr = thirdPtr;
        }
        return p1;
    }
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        ListNode* h1 = reversalList(head1);
        ListNode* h2 = reversalList(head2);
        ListNode* result_head = new ListNode(0);
        ListNode* result_head_index = result_head;
        int shang = 0;
        int remainder = 0;
        while (h1 && h2) {
            int temp_number = h1->val + h2->val + shang;
            shang = temp_number / 10;
            remainder = temp_number % 10;
            ListNode* tempPtr = new ListNode(remainder);
            result_head->next = tempPtr;
            result_head = result_head->next;
            h1 = h1->next;
            h2 = h2->next;
        }
        if (h1 == nullptr) {
            while (h2) {
                int temp_number = h2->val + shang;
                shang = temp_number / 10;
                remainder = temp_number % 10;
                ListNode* tempPtr = new ListNode(remainder);
                result_head->next = tempPtr;
                result_head = result_head->next;
                h2 = h2->next;
            }
        } else if (h2 == nullptr) {
            while (h1) {
                int temp_number = h1->val + shang;
                shang = temp_number / 10;
                remainder = temp_number % 10;
                ListNode* tempPtr = new ListNode(remainder);
                result_head->next = tempPtr;
                result_head = result_head->next;
                h1 = h1->next;
            }
        }
        if (shang == 1) {
            ListNode* tempPtr = new ListNode(shang);
            result_head->next = tempPtr;
            result_head = result_head->next;
        }
        return reversalList(result_head_index->next);
    }
};

因为链表没办法从末尾直接读取数据,可以将链表反转或者借助栈,两种方法最后的加法思路都是计算商和余数

全部评论

相关推荐

嵌入式小辣鸡:包装好一点,校内的奖项可以不用写,校内项目经历最后两点写的太差了,详细讲一下内容,名字变一下。只需要写项目实现了什么,自己在其中做了什么就好,查看图片
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务