一.利用C++、数组实现的栈
//Mystack.h #include<iostream> using namespace std; //利用数组容器实现的一个栈 class Mystack{ private: int MAXSIZE=8;//设定最大容量 int* a;//引用数组名 int num;//栈顶在数组中的下标,下标始终指向下一个空位置,亦即使用容量大小 public: //构造函数创建数组容器 Mystack(){ a = new int[MAXSIZE]; num = 0; } ~Mystack(){ delete[] a; } //返回栈顶元素:栈空返回-1 int top(){ if (num == 0) return -1; return a[num - 1]; } //弹出栈:栈空返回-1 int pop(){ if (num == 0){ cout << "Empty" << endl; return -1; } num--; return a[num]; } //将元素压入栈 void push(int val){ if (num == MAXSIZE){ cout << "full" << endl; return; } a[num] = val; num++; } //返回元素个数 int size(){ return num; } //是否满:1是0否 bool isFull(){ if (num == MAXSIZE) return true; return false; } //是否空:1是0否 bool isEmpty(){ if (num == 0) return true; return false; } };
//test.cpp #include<iostream> #include"Mystack.h" using namespace std; //一些函数功能测试 void main(){ Mystack ms;//创建一个栈 cout <<"is Empty? "<< ms.isEmpty() << endl; cout << "is Full?" << ms.isFull() << endl; int a[] = { 1, 2, 3, 4, 5 }; for (int i = 0; i < 5; i++){ ms.push(a[i]); } cout << "is Empty? "<<ms.isEmpty() << endl; cout << "have " << ms.size() <<" elements"<< endl; for (int i = 0; i < 5; i++){ cout << ms.top() << endl; ms.pop(); } }
时间: 2024-11-02 11:03:44