標籤:
/********************************************************************** * Copyright (c)2015,WK Studios * Filename: stack.h * Compiler: GCC,VS,VC6.0 win32 * Author:WK * Time: 2015 3 29 ************************************************************************/ #include<iostream>using namespace std;const int SIZE=10;class Stack{private: int stck[SIZE];//數組用於存放棧中資料 int tos; //棧頂位置(數組的下標)public:Stack();void push(int ch); //函式宣告向棧中中壓入資料fuction int pop(); //聲明從堆棧中彈出資料fuctionvoid ShowStack(); //聲明顯示堆棧資料function};
/********************************************************************** * Copyright (c)2015,WK Studios * Filename: stack.cpp * Compiler: GCC,VS,VC6.0 win32 * Author:WK * Time: 2015 3 29 ************************************************************************/ #include"stack.h" //建構函式,初始化棧的實現Stack::Stack(){ tos=0; stck[SIZE]=0;} //向棧中壓入資料函數的實現void Stack::push(int ch){ if(tos==SIZE) { cout<<"Stack is full!\n"; return ; } stck[tos]=ch; tos++; cout<<"You have pushed a data into the Stack!\n";} //從棧中彈出資料函數的實現int Stack::pop(){ if(0==tos) { cout<<"Stack is empty!\n"; return 0; } tos--; return stck[tos];}//顯示棧中資料的函數的實現void Stack::ShowStack(){ cout<<"The content of Stack:\n"; if(0==tos) { cout<<"The Stack has no data!\n";return ; } for(int i=tos-1;i>=0;i--) { cout<<stck[i]<<' '; } cout<<'\n';}
/********************************************************************** * Copyright (c)2015,WK Studios * Filename: main.cpp * Compiler: GCC,VS,VC6.0 win32 * Author:WK * Time: 2015 3 29 ************************************************************************/ #include"stack.h"int main(){ cout<<endl;//換行的同時重新整理緩衝區 Stack ss; //定義對象 int x=0; char ch; cout<<" <I>----- push data to Stack!\n"; cout<<" <O>----- pop data from Stack!\n"; cout<<" <S>----- show content of Stack!\n"; cout<<" <Q>----- Quit !!!!!!!\n"; while(1) { cout<<"Please select an item:";cin>>ch;ch=toupper(ch);switch(ch){case 'I': cout<<"Enter the value that you want to push:";cin>>x;ss.push(ch);break;case 'O':x=ss.pop();cout<<"pop "<<x<<" from Stack!\n";break;case 'S':ss.ShowStack();break; case 'Q': return 0;break; default : cout<<"You have iputted a wrong item!!!! Please try again !\n"; continue;} }}
C++ 簡單實現壓棧出棧