考研C语言数据结构-顺序栈(栈的顺序存储实现)

#include <stdio.h>
#include <stdlib.h>

#define maxSize 6

// 定义顺序栈数据类型
typedef struct {

	int data[maxSize];
	int top;
}SqStack;

void initSqStack(SqStack &S) {

	S.top = -1;// 初始化栈顶指针top指向-1位置
}

// 栈空判断
bool isEmpty(SqStack S) {

	if(S.top == -1)
		return true;

	return false;
}

// 入栈
bool push(SqStack &S, int e) {

	// 判断栈是否满
	if(S.top >= maxSize - 1)
		return false;

	S.data[++S.top] = e;

	return true;
}

// 出栈
bool pop(SqStack &S, int &e) {

	if(isEmpty(S))
		return false;

	e = S.data[S.top--];

	return true;
}

// 读栈顶元素
bool getTop(SqStack S, int &e) {

	if(isEmpty(S))
		return false;

	e = S.data[S.top];

	return true;
}

int main(void) {

	SqStack S;

	initSqStack(S);

	push(S, 1);
	push(S, 2);
	push(S, 3);
	push(S, 4);
	push(S, 5);

	int e = -1;

	if(pop(S, e))
		printf("出栈元素:%d\n", e);

	if(pop(S, e))
		printf("出栈元素:%d\n", e);

	if(getTop(S, e))
		printf("栈顶元素:%d\n", e);

	if(pop(S, e))
		printf("出栈元素:%d\n", e);

	if(pop(S, e))
		printf("出栈元素:%d\n", e);

	if(pop(S, e))
		printf("出栈元素:%d\n", e);

	if(isEmpty(S))
		printf("栈已空\n");

	system("pause");
	return 0;
}
posted @ 2022-05-07 19:38  dqlai  阅读(94)  评论(0)    收藏  举报