C++ 簡單實現壓棧出棧

來源:互聯網
上載者:User

標籤:


/**********************************************************************   * 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++ 簡單實現壓棧出棧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.