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

链表相加(二)

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /*
        反转链表
    */
    ListNode* reverseList(ListNode *head) {
        if (head == nullptr || head->next == nullptr) {
            return head;
        }
        // 头插法
        ListNode tmp(0);
        ListNode *newHead = &tmp, *second = head->next;
        while (head) {
            head->next = newHead->next;
            newHead->next = head;
            head = second;
            second = head->next;
        }
        return newHead->next;
    }
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        head1 = reverseList(head1);
        head2 = reverseList(head2);
        ListNode res(0);
        ListNode *cur = &res;
        int c = 0; // 进位
        while (head1 && head2) {
            int tmp = head1->val + head2->val + c;
            c = tmp / 10;
            ListNode *newNode = new ListNode(tmp % 10);
            newNode->next = cur->next;
            cur->next = newNode;
            head1 = head1->next;
            head2 = head2->next;
        }
        while (head1) {
            int tmp = head1->val + c;
            c = tmp / 10;
            ListNode *newNode = new ListNode(tmp % 10);
            newNode->next = cur->next;
            cur->next = newNode;
            head1 = head1->next;
        }
        while (head2) {
            int tmp = head2->val + c;
            c = tmp / 10;
            ListNode *newNode = new ListNode(tmp % 10);
            newNode->next = cur->next;
            cur->next = newNode;
            head2 = head2->next;
        }
        if (c != 0) {
            ListNode *newNode = new ListNode(c);
            newNode->next = cur->next;
            cur->next = newNode;
        }
        return cur->next;
    }
};

全部评论

相关推荐

07-13 14:45
南华大学 Java
北斗导航Compas...:英文和中文之间加个空格,有的句子有句号 有的没。其他没啥问题
点赞 评论 收藏
分享
07-14 12:22
门头沟学院 Java
点赞 评论 收藏
分享
门口唉提是地铁杀:之前b站被一个游戏demo深深的吸引了。看up主页发现是个初创公司,而且还在招人,也是一天60。二面的时候要我做一个登录验证和传输文件两个微服务,做完要我推到github仓库,还要我加上jaeger和一堆运维工具做性能测试并且面试的时候投屏演示。我傻乎乎的做完以后人家跟我说一句现在暂时不招人,1分钱没拿到全是白干
你的秋招第一场笔试是哪家
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-15 17:17
听说过付费实习,没想到这么贵啊我去,要不我给你个腰子吧
哈哈哈,你是老六:这种公司一定要注意啊,不要随便签合同,只要签了后面钱可能回不来,而且你通过法律途径也弄不回
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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