顺序栈的压栈和出栈
#include<iostream>
using namespace std;
const int StackSize=10; class SeqStack
{
public: SeqStack( ) //構造函數,初始化一個空棧{top=-1;} ~SeqStack( ) { } //析構函數為空void Push( int x ) //入棧操作,將元素x入棧 { if (top== StackSize-1) throw "溢出"; data[++top]=x;} int Pop( ) //出棧操作,將棧頂元素彈出{ if (top==-1) throw "溢出"; int x=data[top--]; return x;} int data[StackSize]; //存放棧元素的數組 int top; //棧頂指針,為棧頂元素在數組的下標
}; int main()
{ SeqStack a; for(int i= 1 ; i <= 10; i++) { a.Push(i);} for(int i = 0; i < 10; i++) { int k = 0; k = a.Pop(); cout<< k << endl;}
}
運行結果:
總結