C++ 链栈

#include <iostream>

using namespace std;

struct Node {
    int elem;
    Node *link;
};

class Stack {
public:
    Stack();           //构造函数,构造一个空栈
    ~Stack();          //析构函数,清除掉栈
    void push(int obj);//入栈
    void pop();        //出栈
    void display();    //显示该栈
private:
    Node *top;
};


const int maxsize = 10;  //设置栈最大层数
int n = 1;
Stack::Stack() {              //构造函数
    top = NULL;
    return;
}
Stack::~Stack() {            //析构函数
    Node *temp;
    if (top != NULL) {
        temp = top;
        top = top->link;
        delete temp;
    }
    return;
}
void Stack::push(int obj) {
    if (n <= maxsize) {
        Node * temp;
        temp = new Node;
        temp->link = top;
        temp->elem = obj;
        top = temp;
        n++;
    }
    else cout << "error:该栈已满";
}

void Stack::pop() {
    Node *temp;
    if (top != NULL) {
        temp = top;
        top = top->link;
        delete temp;
        n--;
    }
    else cout << "error:该栈已经是空栈,无法继续出栈";
}
void Stack::display() {
    cout << "该栈从上到下的输出";
    Node *temp;
    temp = top;
    while (temp) {
        cout << temp->elem << " ";
        temp = temp->link;
    }
    cout << "\n";
    return;
}

int main() {
    Stack a;
    int user_input;
    int x;
    cout << "请输入你要入栈的个数";
    cin >> x;
    for (int j = 1; j <= x; j++) {
        cout << "Enter the " << j << "st number:";
        cin >> user_input;
        a.push(user_input);
    }
    a.display();
    a.push(6);
    a.push(7);
    a.display();
    /*a.pop();
    a.pop();
    a.pop();
    a.pop();
    a.display();*/
    return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值