栈的基本操作

#include
#include
#include
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
 
typedef int SElemType;
typedef int Status;
 
//顺序存储结构,动态分配空间
struct SqStack     
{
    SElemType *base;
    SElemType *top;
    int stacksize;
}SqStack;
 
// 创建栈,栈长为预设值
Status InitStack(SqStack &S)      
{
    S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
    if(!S.base) return ERROR;
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;
    return OK;
}
 
//入栈
Status Push(SqStack &S,SElemType e)   
{
    if(S.top-S.base>=S.stacksize)
    {
        S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
        if(S.base) return ERROR;
        S.top=S.base+S.stacksize;
        S.stacksize+=STACKINCREMENT;
    }
    *S.top++=e;
    return OK;
}
 
 //删除栈顶元素
Status Pop(SqStack &S,SElemType &e)   
{
    if(S.top==S.base) return ERROR;
    e=*--S.top;
    return OK;
}
 
//栈顶元素
Status GetTop(SqStack S,SElemType &e)   
{
    if(S.top==S.base) return ERROR;
    e=*(S.top-1);
    return OK;
}
 
//计算栈中元素个数
int StackLength(SqStack S)   
{
    int i=0;
    while(S.top!=S.base)
    {
        i++;
        S.top--;
    }
    return i;
}
 
//遍历栈
Status StackTraverse(SqStack S)
{
    SElemType *p=(SElemType*)malloc(sizeof(SElemType));
    p=S.top;
 
    if(S.top==S.base)
        printf("The Stack is Empty!");
    else
    {
        printf("The Stack is:");
        while(p!=S.base)
        {
            p--;
            printf("% d",*p);
        }
    }
    printf(" ");
    return OK;
}
 
//主函数
int main()
{
    int a;
    SqStack S;
    SElemType x,e;
    if(InitStack(S)) printf("A Stack Has Created. ");
    while(1)
    {
        printf("1:Push 2:Pop 3:Get the Top 4:Return the Length of the Stack 5:Load the Stack 0:Exit Please choose: ");
        scanf("%d",&a);
        switch(a)
        {
        case 1:
            scanf("%d",&x);
            if(!Push(S,x)) printf("Push Error! ");
            else printf("The Element %d is Successfully Pushed! ",x);
            break;
        case 2:
            if(!Pop(S,e)) printf("Pop Error! ");
            else
 
                printf("The Element %d is Successfully Poped! ",e);
            break;
        case 3:
            if(!GetTop(S,e)) printf("GetTop Error! ");
            else printf("The Top Element is %d! ",e);
            break;
        case 4:
            printf("The Length of the Stack is %d! ",StackLength(S));
            break;
        case 5:
            StackTraverse(S);
            break;
        case 0:
            return 1;
        }
    }
}
原文地址:https://www.cnblogs.com/yujon/p/5467616.html