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

链表相加(二)

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* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        if(head1 == nullptr) return head2;
        if(head2 == nullptr) return head1;
        bool overTen = false;
        stack<int> ans;
        stack<int> m_stack1;
        stack<int> m_stack2;
        ListNode* final = new ListNode(0);
        ListNode* cur = final;
        while(head1)
        {
            m_stack1.push(head1->val);
            head1 = head1->next;
        }
        while(head2)
        {
            m_stack2.push(head2->val);
            head2 = head2->next;
        }
        while(!m_stack1.empty() || !m_stack2.empty() || overTen)
        {
            int temp1 = 0;
            int temp2 = 0;
            int sum = 0;
            if(!m_stack1.empty())
            {
                temp1 = m_stack1.top();
                m_stack1.pop();
            }
            if(!m_stack2.empty())
            {
                temp2 = m_stack2.top();
                m_stack2.pop();
            }
            if(overTen)
            {
                sum = temp1 + temp2 + 1;
            }
            else
            {
                sum = temp1 + temp2;
            }
            if(sum >= 10)
            {
                sum = sum - 10;
                overTen = true;
            }
            else
            {
                overTen = false;
            }
            ans.push(sum);
        }
        while(!ans.empty())
        {
            cur->next = new ListNode(ans.top());
            ans.pop();
            cur = cur->next;
        }
        return final->next;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务