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

链表相加(二)

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

//笨蛋方法,使用了三个栈来相加,出错误点在于需要每次给temp new 空间
class Solution {
public:
    /**
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        ListNode* fast = head1, * slow = head2;
        ListNode* nList = new ListNode(0);
        ListNode* nHead = nList;
        int sign = 0;

        stack<ListNode*>stack1, stack2,stack3;
        while (fast)
        {
            stack1.push(fast);
            fast = fast->next;
        }
        while (slow)
        {
            stack2.push(slow);
            slow = slow->next;
        }
        while ((!stack1.empty()) && (!stack2.empty()))
        {
            ListNode* temp = new ListNode(0);
            temp->val = (stack1.top()->val + stack2.top()->val + sign)%10;
            if (stack1.top()->val + stack2.top()->val + sign >= 10)
            {
                sign = 1;
            }
            else
            {
                sign = 0;
            }
            stack1.pop();
            stack2.pop();
            stack3.push(temp);
            cout << temp->val<<"a";
        }
        while (!stack1.empty())
        {
            ListNode* temp = new ListNode(0);
            temp->val = (stack1.top()->val + sign) % 10;
            if (stack1.top()->val + sign >= 10)
            {
                sign = 1;
            }
            else
            {
                sign = 0;
            }
            stack3.push(temp);
            stack1.pop();
            cout << temp->val << "b";
        }
        while (!stack2.empty())
        {
            ListNode* temp = new ListNode(0);
            temp->val = (stack2.top()->val + sign) % 10;
            if (stack2.top()->val + sign >= 10)
            {
                sign = 1;
            }
            else
            {
                sign = 0;
            }
            stack3.push(temp);
            stack2.pop();
            cout << temp->val << "c";
        }
        while (!stack3.empty())
        {
            if (sign == 1)
            {
                nList->val = 1;
            }
            nList->next = stack3.top();
            stack3.pop();
            nList = nList->next;
        }
        if (nHead->val == 0)
        {
            return nHead->next;
        }
        else {
            return nHead;
        }
    }
};

全部评论

相关推荐

喜欢吃蛋糕仰泳鲈鱼是我的神:字节可以找个hr 给你挂了,再放池子捞
点赞 评论 收藏
分享
11-05 07:29
贵州大学 Java
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务