题解 | #链表相加(二)#基于stack的方法

链表相加(二)

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

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <vector>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    stack<ListNode*> getstack(ListNode* head) {
        stack<ListNode*> s;
        while (head) {
            s.push(head);
            head = head->next;
        }
        return s;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        if (head1 == nullptr) return head2;
        if (head2 == nullptr) return head1;
        if (!head1 && !head2) return nullptr;

        stack<ListNode*> s1 = getstack(head1);
        stack<ListNode*> s2 = getstack(head2);
        int carry = 0;
        ListNode* node = new ListNode(0);
        while (!s1.empty() || !s2.empty() || carry) {
          int num1 = s1.empty() ? 0 : s1.top()->val;
            int num2 = s2.empty() ? 0 : s2.top()->val;

            if (!s1.empty()) s1.pop();
            if (!s2.empty()) s2.pop();

            int sum = num1 + num2 + carry;
            carry = sum / 10;
            ListNode* dummy = new ListNode(sum % 10);
            dummy->next=node->next;
            node->next=dummy;
        }
        return node->next;
    }
};

全部评论

相关推荐

zhch7:建议9✌️把学历加黑加粗,如果实在offer可能是觉得佬不会去
投了多少份简历才上岸
点赞 评论 收藏
分享
06-05 19:46
已编辑
武汉大学 后端
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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