WHCSRL 技术网

c语言版顺序栈的基本操作

c语言版顺序栈的基本操作

#include <stdio.h>
#include <stdlib.h>
#define  MaxSize  20
#define false 0
#define true 1;
typedef  struct  SqStack{
	
	int data[MaxSize];
	int top;
	
}SqStack;

void InitStack(SqStack *S){//初始化顺序栈
	S->top=-1;
	
}



int  Push(SqStack *S,int n){//将数据n压入栈中
		if(S->top==MaxSize-1)
			return false;
		S->top++;
		S->data[S->top]=n;
		printf("元素%%d进栈成功
",n);
		return true;
	
}

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

int Pop(SqStack *S,int *a){//栈顶元素出栈,且将数据存储在a中
	int i=S->top;
	if (S->top==-1) {
		return false;
	
	}
	*a=S->data[i];
	S->top--;
	printf("出栈的数据为:%%d
",*a);
	return true;
}

int GetTop(SqStack S){
	
	if (S.top != -1) {
		printf("栈顶元素为:%%d
", S.data[S.top]);
		return true;
	}
	
	else
		return false;
}

int Display(SqStack S){
	printf("此栈中的元素为:");
	for (int i=0; i<=S.top; i++) {
		printf("%%d",S.data[i]);
	}
	printf("
");
	return true;

	
}

int main(){
	SqStack S;
	InitStack(&S);//初始化一个空栈
	Push(&S, 3);//将3进栈
	Push(&S, 4);//将4进栈
	Display(S);//输出栈中元素
	int n;
	Pop(&S, &n);//将栈顶元素出栈,且将元素赋给n
	StackEmpty(S);//判断是否为空
	GetTop(S);//获得栈顶元素
	
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
推荐阅读