栈的基本操作(入栈、出栈)

C++实现入栈、出栈、读栈顶元素、置空栈以及判断栈空否。供参考。


#include<iostream>
#include<stdlib.h>
#define MaxSize 100   //假定预分配的栈空间最多能存放100个表目

using namespace std;

typedef char datatype;     //表面类型为字符
typedef struct{
        datatype s[MaxSize];
        int top;       //栈顶指针 top=-1 即为空栈 
}seqStack;
seqStack st;
datatype x;

using namespace std;

void stack_push(seqStack &st,datatype x);
void stack_pop(seqStack &st,datatype &x);
datatype stack_gettop(seqStack &st);
void stack_clear(seqStack &st);
int stack_empty(seqStack &st);

int main()
{
    st.top=-1; //栈顶赋初值; 
    stack_push(st,'a');
    stack_push(st,'b');
    cout<<stack_gettop(st)<<endl;
    stack_pop(st,x);
    stack_push(st,'c');
    cout<<stack_gettop(st)<<endl;
    
    for(int i=st.top;i>0;i--)
        cout<<st.s[i];
        cout<<endl;
        
    stack_push(st,'d');
    for(int i=0;i<=st.top;i++)
       {
            cout<<i;
            cout<<st.s[i];
       }
    cout<<endl;
    
    system("pause");
    return 0;
} 

void stack_push(seqStack &st,datatype x)
{
    if(st.top>=MaxSize-1)
          cout<<"overflow"<<endl;       //overflow
    else 
         st.s[++st.top]=x;    //push
}

void stack_pop(seqStack &st,datatype &x)
{
    if(st.top==-1)
         cout<<"underflow"<<endl;     //空栈 
    else
        x=st.s[st.top--];
} 

datatype stack_gettop(seqStack &st)
{
     if(st.top==-1)
           cout<<"error"<<endl;
     else 
          return st.s[st.top];          
}

void stack_clear(seqStack &st)
{
     st.top=-1; 
} 

int stack_empty(seqStack &st)
{
    if(st.top==-1)
         return 1;
    else 
         return 0;
}



猜你喜欢

转载自blog.csdn.net/qq_30300695/article/details/80951498