栈的实现-顺序表

声明:

#include "stdio.h"
#include "stdlib.h"

typedef int DataType;

struct SeqStack {
    int MAXNUM;
    //t<MAXNUM,指示栈顶位置,而不是元素个数;
    int t;
    DataType *s;
};
//顺序栈类型的指针类型
typedef struct SeqStack * PSeqStack;

 

//创建空栈
PSeqStack createEmptyStack_seq(int m)
{
    PSeqStack pStack=(PSeqStack)malloc(sizeof(struct SeqStack));
    
    if (pStack!=NULL) 
    {
        pStack->s=(DataType *)malloc(sizeof(DataType) * m);
        
        if(pStack->s)
        {
            pStack->MAXNUM=m;
            pStack->t=-1;
            return pStack;
        }
        else
        {
            free(pStack);
        }
    }
    
    printf("out of space!! \n");
    return NULL;
}

 

//判断pStack是否为空栈,如果是,则返回1,否则返回0;
int isEmptyStack_seq(PSeqStack pStack)
{
    return (pStack->t==-1);
}

 

 

//进栈操作
void push_seq(PSeqStack pStack,DataType x)
{
    if (pStack->t>=pStack->MAXNUM-1) 
    {
        printf("overflow! \n");
    }
    else
    {
        pStack->t=pStack->t+1;
        pStack->s[pStack->t]=x;
    }
}

 

 

//出栈操作
void pop_seq(PSeqStack pStack)
{
    if (pStack->t==-1) 
    {
        printf("Underflow! \n");

    }
    else
    {
        pStack->t=pStack->t-1;
    }
}

 

//取栈顶元素
DataType top_seq(PSeqStack pStack)
{
    if (pStack->t==-1) 
    {
        printf("empty ! \n");
    }
    else
    {
        return (pStack->s[pStack->t]);
    }
}

 

测试:

int main()
{
    PSeqStack pStack;
    pStack=createEmptyStack_seq(10);
    push_seq(pStack,3);
    push_seq(pStack,6);
    push_seq(pStack,1);
    push_seq(pStack,0);
    push_seq(pStack,7);

    printf("%d ",pStack->s[pStack->t]);

    pop_seq(pStack);
    printf("%d ",pStack->s[pStack->t]);

    return 1;
}

posted on 2012-05-11 10:22  yucong  阅读(225)  评论(0)    收藏  举报

导航