用c++写一个链栈

来源:互联网 发布:取石子java 编辑:程序博客网 时间:2024/05/16 08:58

1.建立一个头文件stack.h,在头文件中声明链栈的各种操作

#include <iostream>struct Node {int elem;Node *link;};class Stack {public:Stack();           //构造函数,构造一个空栈~Stack();          //析构函数,清除掉栈void push(int obj);//入栈void pop();        //出栈void display();    //显示该栈private:Node *top; };
2.新建一个.cpp文件,用来定义已经声明的各个操作并且测试

#include"stack.h"#include <iostream>using namespace std;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;}