C语言实现栈

275 阅读1分钟

概述

使用C语言顺序表数据结构实现栈。

代码

头文件、声明等

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#define true 1
#define false 0
#define bool char
#define MAX_SIZE 10
//链表数据类型
typedef int ElementType;


typedef struct Stack
{
	ElementType data[MAX_SIZE];
	int top;//栈顶指针(数组下标)

} Stack;

bool initStack(Stack* S);
bool push(Stack* S, ElementType data);
bool pop(Stack* S);
bool getTop(Stack* S, ElementType* x);

main函数

int main() {
	Stack S;
	initStack(&S);
	push(&S, 1);
	push(&S, 2);
	push(&S, 3);
	ElementType x;
	pop(&S);
	getTop(&S, &x);
	printf("%d", x);
	return 0;
}

初始化

bool initStack(Stack* S) {
	for (int i = 0; i < MAX_SIZE; i++) {
		S->data[i] = 0;
	}
	S->top = -1;
	return true;
}

判断为空

bool isEmpty(Stack* S) {
	if (S->top == -1) {
		return true;
	}
	return false;
}

入栈

bool push(Stack* S, ElementType data) {
	if (S->top == MAX_SIZE - 1) {
		return false;
	}
	S->data[++(S->top)] = data;
	return true;
}

出栈

bool pop(Stack* S) {
	if (S->top == -1) {
		return false;
	}
	S->data[S->top] = 0;
	S->top--;
	return true;
}

获取栈顶元素

bool getTop(Stack* S, ElementType *x) {
	if (S->top == -1) {
		return false;
	}
	*x = S->data[S->top];
	return true;
}