牛客题霸 [两个链表生成相加链表] C++题解/答案

牛客题霸 [两个链表生成相加链表] C++题解/答案

题目描述

假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。

题解

先用两个栈来存两个链表的数,然后两个栈一起弹出,并加法运算后,将%10结果存在新的链表里
整个过程比较直接

代码:

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        stack<int> a;
        stack<int> b;
        while (head1 || head2)
        {
            if (head1)
            {
                a.push(head1->val);
                head1 = head1->next;
            }
            if (head2)
            {
                b.push(head2->val);
                head2 = head2->next;
            }
        }
        int sum = 0, carry = 0;
        ListNode* pre = new ListNode(-1);
        while (!a.empty() || !b.empty() || carry != 0)
        {
            int x = 0, y = 0;
            if (!a.empty())
            {
                x = a.top();
                a.pop();
            }
            if (!b.empty())
            {
                y = b.top();
                b.pop();
            }
            sum = x + y + carry;
            carry = sum / 10;
            sum = sum % 10;
            ListNode* cur = new ListNode(sum);
            cur->next = pre->next;
            pre->next = cur;
        }
        return pre->next;
    }
};
posted @ 2020-11-30 11:07  回归梦想  阅读(238)  评论(0编辑  收藏  举报