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

链表相加(二)

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
  public:
    /**
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    ListNode* Reverse(ListNode* head) {
        if(!head) return nullptr;
        ListNode*cur = head;
        ListNode*pre = nullptr;
        while(cur)
        {
            ListNode*temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;

        // if (head == NULL)
        //     return NULL;
        // ListNode* cur = head;
        // ListNode* pre = nullptr;
        // while (cur != nullptr) {
        //     //断开链表,要记录后续一个
        //     ListNode* temp = cur->next;
        //     //当前的next指向前一个
        //     cur->next = pre;
        //     //前一个更新为当前
        //     pre = cur;
        //     //当前更新为刚刚记录的后一个
        //     cur = temp;
        // }
        // return pre;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        if (head1 == nullptr)
            return head2;
        if (head2 == nullptr)
            return head1;

        head1 = Reverse(head1);
        head2 = Reverse(head2);
        ListNode* head = nullptr;
        int carry = 0;
        while (head1 || head2 || carry != 0) {
            int val1 = head1 == nullptr ? 0 : head1->val;
            int val2 = head2 == nullptr ? 0 : head2->val;
            int temp = val1 + val2 + carry;
            carry =temp/ 10;
            temp %= 10;

            ListNode* p = new ListNode(temp);
            p->next = head;
            head = p;

            if (head1) {
                head1 = head1->next;
            }
            if (head2) {
                head2 = head2->next;
            }
        }
        return head;
    }
};

记模板记模板!

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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