1. 程式人生 > >順序棧初始化,判空,進棧,出棧,列印

順序棧初始化,判空,進棧,出棧,列印

#include<iostream>

#define maxSize 100     //後面沒有分號  ;   

using namespace std;

typedef struct //順序棧的定義
{
         int data[maxSize];//資料
         int top;//棧頂指標

}SqStack;

void initStack(SqStack &st)
{
      st.top=-1;//初始化只需要將棧頂指標置為-1就行了,表明一個空棧。為0時,表示還可以儲存一個元素,因為陣列的下標從0開始
}

int isEmpty(SqStack st)//判斷棧空
{
        if(st.top==-1)
             cout<<"kong"<<endl;
        else
              cout<<"feikong"<<endl;

        return 0;
}

int Push(SqStack &st,int x)//進棧
{
        if(st.top==maxSize-1)
        {
                return 0;
        }
        ++(st.top);//進棧變動棧頂指標,在存入元素
         st.data[st.top]=x;

         return -1;
}

int Pop(SqStack &st,int &x)//出棧
{
        if(st.top==-1)
        {
              return 0;
         }
         x=st.data[st.top];//出棧先取出元素,再變動棧頂指標
         --(st.top);
         return -1;
}

void print(SqStack st)//列印
{
         while(st.top!=-1)
         {
             cout<<st.data[st.top]<<endl;
             st.top--;
         }
}

int main()
{
      SqStack Stack1;
      initStack(Stack1);
      isEmpty(Stack1);
      Push(Stack1,2);
      Push(Stack1,4);
      print(Stack1);

       int a;
       Pop(Stack1,a);
       print(Stack1);
       cout<<a<<endl;

       return 0;

}

列印:kong

             4

             2

             4

             2

             4