题解 | 链表相加(二)

链表相加(二)

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

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
  public:
//ReverseList用于翻转链表
    ListNode* ReverseList(ListNode* head) {
        ListNode* n1 = nullptr;
        ListNode* n2 = head;
        if (n2 == nullptr) {
            return head;
        }
        ListNode* n3 = head->next;

        while (n2) {
            n2->next = n1;
            n1 = n2;
            n2 = n3;
            if (n2)//这里需要注意
                n3 = n2->next;
        }
        return n1;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        ListNode* ptr1 = ReverseList(head1);//9->3->7 ----- 7->3->9
        ListNode* ptr2 = ReverseList(head2);//6->3 -----    3->6
        int ret = 0;
        ListNode* head = nullptr;//相加之后的链表
        ListNode* ptr = head;
        int count = 1;//用来记录头节点
        while (ptr1 || ptr2) {
            int sum = 0;
            if (ptr1) {
                sum += ptr1->val;
                ptr1 = ptr1->next;
            }
            if (ptr2) {
                sum += ptr2->val;
                ptr2 = ptr2->next;
            }
            sum += ret;
            //创建节点;
            ListNode* cur = new ListNode(sum % 10);
            if (count == 1) {
                head = cur;
                ptr = head;
                ret = sum / 10;
                count++;
            } else {
                ptr->next = cur;
                ptr = cur;
                ret = sum / 10;
            }
        }
        if (ret) {
            ListNode* cur = new ListNode(ret);
            ptr->next = cur;
        }
        return ReverseList(head);//最后需要将链表翻转
    }
};

全部评论
点赞 回复 分享
发布于 05-26 12:40 四川

相关推荐

点赞 评论 收藏
分享
09-16 17:32
门头沟学院 Java
顺顺超爱学:1.熟悉Java编程语言,熟悉集合,多线程,IO,反射等核心知识,了解线程池,ThreadLocal等进阶知识; 2.熟悉Mysql数据库,熟练使用sql,熟悉索引,存储引擎,事务原理,MVCC,锁机制,了解sql优化; 3.熟悉Redis缓存,了解常见的数据类型,了解缓存常见问题及其解决方案,了解使用Redis实现的分布式锁方案; 4.熟悉Javaweb开发框架,熟悉spring,springmvc,mybatis等,了解IOC,AOP等; 5.熟悉微服务开发框架,熟悉SpringBoot,SpringCloud,包括Nacos,OpenFeign,Gateway等核心组件; 6.熟悉Rabbitmq消息队列,熟练使用消息模型,了解架构,消息可靠性,死信队列,延迟消息等;
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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