#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;
}