实现链表相加,链表 1为 3->7->2,链表 2 为 2->4,最后生成新的结果链表为 3->9->6

#include 
#include 

using namespace std;

class ListNode {
public:
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        if (head1 == nullptr) return head2;
        if (head2 == nullptr) return head1;

        stack<ListNode*> s1;
        stack<ListNode*> s2;

        while (head1 != nullptr) {
            s1.push(head1);
            head1 = head1->next;
        }

        while (head2 != nullptr) {
            s2.push(head2);
            head2 = head2->next;
        }

        int flag = 0;
        ListNode* newHead = nullptr;

        while (!s1.empty() || !s2.empty() || flag > 0) {
            int sum = flag;

            if (!s1.empty()) {
                sum += s1.top()->val;
                s1.pop();
            }

            if (!s2.empty()) {
                sum += s2.top()->val;
                s2.pop();
            }

            flag = sum / 10;
            ListNode* newNode = new ListNode(sum % 10);
            newNode->next = newHead;
            newHead = newNode;
        }

        return newHead;
    }
};

int main() {
    ListNode* head1 = new ListNode(3);
    head1->next = new ListNode(7);
    head1->next->next = new ListNode(2);

    ListNode* head2 = new ListNode(2);
    head2->next = new ListNode(4);

    Solution solution;
    ListNode* result = solution.addInList(head1, head2);

    while (result != nullptr) {
        cout << result->val << " ";
        result = result->next;
    }

    return 0;
}

你可能感兴趣的:(工作,链表,算法,数据结构)