设为首页 加入收藏

TOP

顺序栈的c语言实现
2015-01-22 21:30:47 来源: 作者: 【 】 浏览:57
Tags:顺序 语言 实现

1.顺序栈结构

typedef struct
{
        SElemType data[MAXSIZE];
        int top; /* 用于栈顶指针 */
}SqStack;


2.构造一个空栈S

Status InitStack(SqStack *S)
{ 
        /* S.data=(SElemType *)malloc(MAXSIZE*sizeof(SElemType)); */
        S->top=-1;
        return OK;
}


3.把S置为空栈

Status ClearStack(SqStack *S)
{ 
        S->top=-1;
        return OK;
}


4.若栈S为空栈,则返回TRUE,否则返回FALSE

Status StackEmpty(SqStack S)
{ 
        if (S.top==-1)
                return TRUE;
        else
                return FALSE;
}


5.返回S的元素个数,即栈的长度

int StackLength(SqStack S)
{ 
        return S.top+1;
}


6.若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR

Status GetTop(SqStack S,SElemType *e)
{
        if (S.top==-1)
                return ERROR;
        else
                *e=S.data[S.top];
        return OK;
}


7. 插入元素e为新的栈顶元素

Status Push(SqStack *S,SElemType e)
{
        if(S->top == MAXSIZE -1) /* 栈满 */
        {
                return ERROR;
        }
        S->top++;				/* 栈顶指针增加一 */
        S->data[S->top]=e;  /* 将新插入元素赋值给栈顶空间 */
        return OK;
}



8.若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR

Status Pop(SqStack *S,SElemType *e)
{ 
        if(S->top==-1)
                return ERROR;
        *e=S->data[S->top];	/* 将要删除的栈顶元素赋值给e */
        S->top--;				/* 栈顶指针减一 */
        return OK;
}


9.从栈底到栈顶依次对栈中每个元素显示

Status StackTraverse(SqStack S)
{
        int i;
        i=0;
        while(i<=S.top)
        {
                visit(S.data[i++]);
        }
        printf("\n");
        return OK;
}


Status visit(SElemType c)
{
        printf("%d ",c);
        return OK;
}


参考<<大话数据结构>>

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C语言学习_三分查找 下一篇两栈共享空间的c语言实现

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: