#include <stdio.h>  
#include "stack.h"

int main(void)
{
SqStack st;
ElemType e;

InitStack(&st);
printf("栈%s/n", (StackEmpty(st) == 0 ? "" : "不空"));
printf("a进栈/n"); Push(&st, 'a');
printf("b进栈/n"); Push(&st, 'b');
printf("c进栈/n"); Push(&st, 'c');
printf("d进栈/n"); Push(&st, 'd');
printf("栈%s/n", (StackEmpty(st) == 1 ? "" : "不空"));
GetTop(st, &e);
printf("栈顶元素:%c/n", e);
printf("出栈次序:");

while((StackEmpty(st))) //栈空返回0,否则返回-1
{
Pop(&st, &e);
printf("%c ", e);
}
printf("/n");

return 0;
}


[cpp] view plaincopyprint?
#ifndef STACK
#define STACK

#define StackSize 100
typedef char ElemType;

typedef struct
{
ElemType data[StackSize]; //保存栈中元素
int top; //栈指针
}SqStack;

void InitStack(SqStack *st); //初始化栈

int Push(SqStack *st, ElemType x); //入栈操作

int Pop(SqStack *st, ElemType *x); //出栈操作

int GetTop(SqStack st, ElemType *x); //取栈顶元素

int StackEmpty(SqStack); //判断栈空操作


#endif


[cpp] view plaincopyprint?
#include <stdio.h>
#include "stack.h"

/************************************************
** 函数名:void InitStack(SqStack *st)
** 功能: 初始化栈
** 描述: 无
** 作者: 庞辉
************************************************
*/

void InitStack(SqStack *st)
{
st->top = -1; //注意思考为什么初始化为-1呢?
}

/************************************************
** 函数名:int Push(SqStack *st, ElemType x)
** 功能: 入栈操作
** 描述: 栈满返回-1,成功返回0
** 作者: 庞辉
************************************************
*/

int Push(SqStack *st, ElemType x)
{
if(StackSize - 1 == st->top) //从0开始计算
{
return -1;
}
else
{
st->top++;
st->data[st->top] = x;
return 0;
}
}

/************************************************
** 函数名:int Pop(SqStack *st, ElemType *x)
** 功能: 出栈操作
** 描述: 栈空返回-1,成功返回0
** 作者: 庞辉
************************************************
*/

int Pop(SqStack *st, ElemType *x)
{
if(-1 == st->top)
{
return -1;
}
else
{
*x = st->data[st->top];
st->top--;
return 0;
}
}

/************************************************
** 函数名:int GetTop(SqStack st, ElemType *x)
** 功能: 取栈顶元素
** 描述: 栈空返回-1,成功返回0
** 作者: 庞辉
************************************************
*/

int GetTop(SqStack st, ElemType *x)
{
if(-1 == st.top)
{
return -1;
}
else
{
*x = st.data[st.top];
return 0;
}
}

/************************************************
** 函数名:int StackEmpty(SqStack st)
** 功能: 判断栈空操作
** 描述: 栈空返回0,否则返回-1
** 作者: 庞辉
************************************************
*/

int StackEmpty(SqStack st)
{
if(-1 == st.top)
{
return 0;
}
else
{
return -1;
}
}



原文地址:https://www.cnblogs.com/pang123hui/p/2309941.html