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

链表相加(二)

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */

    ListNode* reverse(ListNode* head)
    {
        if (head != nullptr) {
            ListNode* pCur = head;
            ListNode* pNext = pCur->next;
            while (pCur != nullptr && pNext != nullptr) {
                ListNode* pNNext = pNext->next;

                pNext->next = pCur;
                pCur = pNext;
                pNext = pNNext;
            }
            head->next = nullptr;
            head = pCur;
        }
        
        return head;
    }

    ListNode* addInList(ListNode* head1, ListNode* head2) {
        head1 = reverse(head1);
        head2 = reverse(head2);
        
        auto pCur = new ListNode(0);

        bool bAdd = false;
        while (head1 != nullptr || head2 != nullptr) {
            int head1Value = head1 != nullptr ? head1->val : 0;
            int head2Value = head2 != nullptr ? head2->val : 0;

            int nAddVal = head1Value + head2Value + bAdd;
            bAdd = nAddVal >= 10 ? true : false;
            nAddVal = nAddVal >= 10 ? nAddVal - 10 : nAddVal;

            pCur->val = nAddVal;

            auto pPer = new ListNode(0);
            pPer->next = pCur;
            pCur = pPer;

            if(head1 != nullptr) head1 = head1->next;
            if(head2 != nullptr) head2 = head2->next;
        }

        if(bAdd)
            pCur->val = 1;
        else
        {
            auto temp = pCur;
            pCur = pCur->next;
            delete temp;
        }

        return pCur;
    }
};

全部评论

相关推荐

karis_aqa:和hr没关系,都是打工的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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