微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

stack

#include<bits/stdc++.h>
using namespace std;

class node {
public:
    int data;
    node* next;
    node* prev;
};

class stack1 {
public:
    stack1();
    void push(node* &temp, int data);
    void pop(node* &temp);
    void show(node* &temp);
    node* head;
};

stack1::stack1() {
    head = new node;
    head->prev = NULL;
    head->next = NULL;

}

void stack1::push(node* &temp, int data) {
    if (temp->next == NULL) {
     //   cout << "push"<<data << endl;
        node* temp1 = new node;
        temp1->next = NULL;//没有这句会访问冲突,后面的show() 也会出错 i dont kNow why
        temp1->data = data;
    //    cout << temp1->data << endl;
        temp->next = temp1;

        temp1->prev = temp;
     //   cout << temp1->prev->next->data << endl;
    }
    else push(temp->next, data);
}

void stack1::pop(node*& temp) {
    node* p = new node;
    if (!temp->next) {
        if (!temp->prev) cout << "栈为空" << endl;
        if (temp->prev) {
            temp->prev->next = NULL;
            return;
        }
    }
    
    else {
        pop(temp->next);
    }
}

vector<int> vec;
vector<int>::iterator i;
void stack1::show(node*& temp) {
    node* p = new node;
    if (temp->next) {
        p = temp->next;
        while (p) {
            cout << p->data << " ";
            p = p->next;
        }
    }
}
void fun(int n,int a ,stack1* temp) {
    if (n == 1) {
        temp->push(temp->head, a);
        temp->show(temp->head);
        reverse(vec.begin(), vec.end());
        for (i = vec.begin(); i < vec.end(); i++) {
            cout << *i << " ";
        }
        cout << endl;

    }
    else { 
        temp->pop(temp->head);
        temp->show(temp->head);
        reverse(vec.begin(), vec.end());
        for (i = vec.begin(); i < vec.end(); i++) {
            cout << *i << " ";
        }
        cout << endl;
    }
}

int main() {
    int n,a;
    stack1* sta = new stack1;
    while (cin >> n>>a) {
        fun(n, a, sta);
    }
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐