题解 | 链表相加(二)

/**
 * 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);
    }
};

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

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-18 18:30
点赞 评论 收藏
分享
白火同学:先说结论,准大三不是特别好找实习,boss沟通300+没有实习是很正常的情况。一是暑期实习时间太短了,二是在这么多准大四都找不到实习,从实习时间和掌握技术层面,企业会优先看他们。 再说简历,其实985本+准大三到这水平的简历也很优秀了,要说的话,项目经历可以再优化一下,可以基本围绕采取STAR原则,分为项目概述、技术架构、技术亮点、实现结果,再发给AI润色一下。 最后说操作,准大三的话,如果想找实习那就多投,不过现在也7月中旬了,时间上已经略晚了。如果7月底实在找不到,也可以多刷点算法,多学点技术,这实习也不至于一定得有,当然有更好。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
快点约我面试吧
投递百度等公司10个岗位
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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