C语言实现判空栈&顺序栈的初始化&进栈&出栈&取栈顶元素

栈是一张特殊的线性表,既可采用顺序存储结构存储,也可以采用链式存储结构存储。

下面介绍采用顺序结构存储的栈的相关基本操作,用一个int top 来作为栈顶的指针,指明当前栈顶的位置,空栈时s -> top = -1,入栈时s ->top ++;出栈时s -> top --;将data和top封装在一个结构中。代码如下:

#include 
#define MAXSIZE 100
#include 
typedef int datatype;
typedef struct {
	int data[MAXSIZE];
	int top;
}SeqStack; 
//初始化栈 
SeqStack *Init_SeqStack(){
	SeqStack *S;
	S = (SeqStack*)malloc(sizeof(SeqStack));
	S -> top = -1;
	return S;
}
//判空栈 
int Empty_SeqStack(SeqStack *S){
if(S -> top == -1)
return 1;
else 
return 0;
}
//入栈 
int push_SeqStack(SeqStack *S,int x){
if(S -> top == MAXSIZE - 1)
return 0;
else{
	S ->top ++;
	S ->data[S ->top] = x;
	return 1;
}
}
//出栈 
int pop_SeqStack(SeqStack *S,int *x){
if(Empty_SeqStack(S))
return 0;
else{
	//把栈顶元素存入变量x即y 
	*x = S -> data[S ->top];
	S -> top --;
	return 1;
}
}
//取栈顶元素 
int Top_SeqStack(SeqStack *S){
	if(Empty_SeqStack(S))
	return 0;
	else
	return S ->data[S ->top];
}
//打印输出栈中元素 
void printfNode(SeqStack *S){
for(int i= 0; i <= S ->top; i ++){
	printf("%d ", S ->data[i]);
}
printf("\n");
} 

int main(){
	SeqStack *S;
	S = Init_SeqStack();
	
	printf("输入入栈数据:");
	int a;
	scanf("%d",&a);
	while(a != -1){
		push_SeqStack(S,a);
		scanf("%d",&a);
	}
	
	printf("栈中的数据元素是:");
	printfNode(S);
	
	int y;
	pop_SeqStack(S,&y);
	printf("出栈的数据元素是:%d\n", y);
	printf("出栈后栈中的数据元素是:"); 
	printfNode(S);
	
	printf("栈顶元素是:%d",Top_SeqStack(S));
} 

运行结果如下:

C语言实现判空栈&顺序栈的初始化&进栈&出栈&取栈顶元素_第1张图片

你可能感兴趣的:(C语言数据结构)