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

链表相加(二)

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* addInList(ListNode* head1ListNode* head2) {

        // write code here

        if(!head1) return head2;

        if(!head2) return head1;

        head1 = reverse(head1);

        head2 = reverse(head2);

        ListNode* p1 = head1;

        ListNode* p2 = head2;

        ListNode* res = new ListNode(-1);

        ListNode* p3 = res;

        int m = 0;

        while(p1!=NULL||p2!=NULL){

            int val1 = p1==NULL ? 0:p1->val;

            int val2 = p2==NULL ? 0:p2->val;

            int sum =val1 + val2 +m;

            m = sum / 10;

            sum = sum % 10;

            ListNode* temp = new ListNode(sum);

            p3->next = temp;

            p3 = temp;

            if(p1!=NULL) p1 = p1->next;

            if(p2!=NULL) p2 = p2->next;

            cout<<temp->val<<" ";

        }

        if(m!=0){

            ListNode* temp = new ListNode(m);

            p3->next = temp;

        }

        res = reverse(res->next);

        return res;

    }

    ListNode* reverse(ListNode* head){

        if(!head) return NULL;

        ListNode* pre = nullptr;

        ListNode* nex;

        ListNode* cur = head;

        while(cur){

            nex = cur->next;

            cur->next = pre;

            pre = cur;

            cur = nex;

        }

        return pre;

        

    }

};

全部评论

相关推荐

想run的马里奥在学...:这个学历帮你扫平百分之80的障碍,投就完了,这会找不到就等3月暑期一样能找到
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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