方法一:

#include<stdio.h>
#include<malloc.h>
#define Maxsize 100
typedef int dataType;
typedef struct{
dataType data[Maxsize];
int top;
}SeqStack;
//创建顺序栈
SeqStack *createStack(){
SeqStack *s = (SeqStack*)malloc(sizeof(SeqStack));
s->top = -1;
return s;
}
//判断栈空
int empty(SeqStack *s){
return s->top == -1;
}
//判断栈是否满
int full(SeqStack *s){
return s->top == Maxsize-1;
}
//进栈
void push(SeqStack *s,dataType x){
if(full(s)) exit(1);
s->data[++s->top] = x;
}
//出栈
void pop(SeqStack *s){
if(empty(s)) exit(1);
s->top--;
}
//取栈顶元素的值
dataType top(SeqStack *s) {
if(empty(s)) exit(1);
return s->data[s->top];
}
//取栈的元素个数
int num(SeqStack *s){
return s->top+1;
}
//遍历整个栈
void outStack(SeqStack *s){
for(int i=s->top;i>=0;i--){
printf("%d ",s->data[i]);
}
}
int main()
{
SeqStack *s = createStack();
push(s,80);
push(s,90);
push(s,70);
push(s,60);
pop(s);
printf("栈顶元素为:");
printf("%d ",top(s));
printf("\n");
printf("当前栈的所有元素为:");
outStack(s);
}

顺序栈的基本操作_#define

方法二:

#include<stdio.h>
#define MaxSize 50
typedef int ElemType;

//定义栈结构体
typedef struct
{
ElemType data[MaxSize];
int top;
}SqStack;


//初始化栈
void InitStack(SqStack &S)
{
S.top = -1;
}

//判断栈是否为空
bool StackEmpty(SqStack S)
{
if(S.top == -1)
return true; //栈为空
else
return false;
}

//入栈
bool Push(SqStack &S,ElemType x)
{
if(S.top == MaxSize-1)
return false;
S.data[++S.top] = x;
return true;
}

//出栈
bool Pop(SqStack &S,ElemType x)
{
if(S.top == -1)
return false;
x = S.data[S.top--];
printf("%d\n",x);
//为查看栈的出栈元素
return true;
}

//获取栈顶元素
bool GetTop(SqStack S,ElemType &x)
{
if(S.top == -1)
return false;
x = S.data[S.top];
printf("%d\n",x);
//为查看栈的栈顶元素
return true;
}


int main()
{
SqStack s;
int m,x;
InitStack(s);
Push(s,3);
Push(s,9);
Push(s,17);
Pop(s,x);
m = StackEmpty(s);
GetTop(s,x);
printf("%d\n",m);
}


顺序栈的基本操作_出栈_02