俩个单链表生成相加链表

#include "List.h"
#include <stack>
using namespace std;
/*解法1:利用栈*/

Node* addList1(Node* head1, Node* head2)
{
    stack<int> sh1;
    stack<int> sh2;

    Node* cur = head1;
    while(cur)
    {
        sh1.push(cur->value);
        cur = cur->next;
    }
    cur = head2;
    while(cur)
    {
        sh2.push(cur->value);
        cur = cur->next;
    }

    int ca = 0;
    int n1 = 0;
    int n2 = 0;
    int n = 0;
    Node* pre = nullptr;
    cur = nullptr;
    while(!sh1.empty() || !sh2.empty())
    {
        if(!sh1.empty())
        {
            n1 = sh1.top();
            sh1.pop();
        }
        else
            n1 = 0;

        if(!sh2.empty())
        {
            n2 = sh2.top();
            sh2.pop();
        }
        else
            n2 = 0;

        n = n1 + n2 + ca;
        pre = cur;
        cur = new Node(n % 10);
        cur->next = pre;
        ca = n / 10;
    }
    if(ca == 1)
    {
        pre = cur;
        cur = new Node(1);
        cur->next = pre;
    }
    return cur;
}
/*解法1:利用链表的逆序求解*/

Node* reverseList(Node* head)
{
   Node* pre  = nullptr;
   Node* next = nullptr;
   while(head)
   {
       next = head->next;
       head->next = pre;
       pre = head;
       head = next;
   }
   return pre;
}
Node* addList2(Node* head1, Node* head2)
{
    head1 = reverseList(head1);
    head2 = reverseList(head2);

    int ca = 0;
    int n1 = 0;
    int n2 = 0;
    int n = 0;
    Node* c1 = head1;
    Node* c2 = head2;
    Node* node = nullptr;
    Node* pre = nullptr;
    while(c1 || c2)
    {
        n1 = c1 ? c1->value : 0;
        n2 = c2 ? c2->value : 0;
        n = n1 + n2 + ca;
        pre = node;
        node = new Node(n % 10);
        node->next = pre;
        ca = n / 10;

        c1 = c1 ? c1->next : nullptr;
        c2 = c2 ? c2->next : nullptr;
    }
    if(ca == 1)
    {
        pre = node;
        node = new Node(1);
        node->next = pre;
    }
    head1 = reverseList(head1);
    head2 = reverseList(head2);
    return node;
}

int main()
{
    Node* pNode0 = new Node(0);
    Node* pNode1 = new Node(1, pNode0);
    Node* pNode2 = new Node(2, pNode1);

    Node* pNode3 = new Node(2);
    Node* pNode4 = new Node(1, pNode3);
    Node* pNode5 = new Node(0, pNode4);

    Print(addList1(pNode2, pNode5));
    cout << "========================" << endl;
    Print(addList2(pNode2, pNode5));
}

猜你喜欢

转载自blog.csdn.net/wzc2608/article/details/80676076