Leetcode刷题笔记题解(C++):BM11 链表相加(二)

2023-12-13 06:12:42

思路:先对两个链表进行反转,反转求和注意进位运算,求和完成之后再进行反转得到结果

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <cstddef>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        ListNode* phead1 = ReverseList(head1);
        ListNode* phead2 = ReverseList(head2);
        int  i= 0;
        ListNode* result = new ListNode(0);
        ListNode* ret = result;
        while(phead2||phead1||i>0){
            int val1 = phead1?phead1->val:0;
            int val2 = phead2?phead2->val:0;
            int sum = val1 + val2 + i;
            i = sum/10;
            sum = sum%10;
            ret->next = new ListNode(sum);
            ret = ret->next;
            if(phead1) phead1 = phead1->next;
            if(phead2) phead2 = phead2->next;
        }
        return ReverseList(result->next);

    }


    ListNode* ReverseList(ListNode* head){
        ListNode* ret = nullptr;
        ListNode* temp = nullptr;
        while(head){
            temp = head->next;
            head->next = ret;
            ret = head;
            head = temp;
        }
        return ret;
    }

};

文章来源:https://blog.csdn.net/qq_27524749/article/details/134842335
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。