栈的代码

来源:互联网 发布:PHP api创建窗口 编辑:程序博客网 时间:2024/04/28 01:19

代码:

#include<stdio.h>
#include<stdlib.h>
#define MaxSize 1000
typedef struct Stack
{
    int *data;
    int top;
}Stack;
int InitStack(Stack *s)
{
    s->data=(int *)malloc(sizeof(int)*MaxSize);
    if(!s->data)
        return 0;
    s->top=-1;
    return 1;
}
void DestoryStack(Stack *s)
{
    free(s->data);
    s->data=NULL;
    s->top=-1;
}
void ClearStack(Stack *s)
{
    s->top=-1;
}
int StackEmpty(Stack s)
{
    // return s.top==-1;
    if(s.top==-1)
        return 1;
    return 0;
}
int StackLength(Stack s)
{
    return s.top+1;
}
int GetTop(Stack s)
{
    return s.data[s.top];
}
int Push(Stack *s,int val)
{
    if(s->top+1==MaxSize)
        return 0;
    s->data[++s->top]=val;
    return 1;
}
int Pop(Stack *s)
{
    if(StackEmpty(*s))
        return 0;
    s->top--;
    return 1;
}
void StackTraverse(Stack s)
{
    int i;
    for(i=s.top;i>=0;i--)
        printf("%d%c",s.data[i],i==0?'\n':' ');
}
int main()
{
    Stack *s;
    s=(Stack *)malloc(sizeof(Stack));
    InitStack(s);
    Push(s,1);
    Push(s,2);
    Push(s,3);
    Push(s,4);
    while(StackEmpty(*s)==0)
    {
        printf("%d ",GetTop(*s));
        Pop(s);
    }


    return 0;
}

0 0