C语言实现栈

概述

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

代码

头文件、声明等

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函数

c 复制代码
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;
}

初始化

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

判断为空

c 复制代码
bool isEmpty(Stack* S) {
	if (S->top == -1) {
		return true;
	}
	return false;
}

入栈

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

出栈

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

获取栈顶元素

c 复制代码
bool getTop(Stack* S, ElementType *x) {
	if (S->top == -1) {
		return false;
	}
	*x = S->data[S->top];
	return true;
}
相关推荐
啧不应该啊5 小时前
Day1 Python 与 C 的类型区别
c语言·开发语言
cen__y5 小时前
Linux07(信号01)
linux·运维·服务器·c语言·开发语言
木木_王9 小时前
嵌入式Linux学习 | 数据结构 (Day05) 栈与队列详解(原理 + C 语言实现 + 实战实验 + 易错点剖析)
linux·c语言·开发语言·数据结构·笔记·学习
Joseph Cooper10 小时前
Linux HID 子系统实战:从虚拟键盘到 input 事件上报
linux·c语言·计算机外设
啧不应该啊11 小时前
Day1 python与c宏观区别
c语言·开发语言
OneT1me11 小时前
CVE-2026-31431 的C语言版本
c语言·开发语言·安全威胁分析
爱编码的小八嘎12 小时前
C‘语言完美演绎9-11
c语言
一行代码一行诗++13 小时前
C语言中if的使用
c语言·c++·算法
来生硬件工程师13 小时前
【程序库】 MutiButton 按键库
c语言·笔记·stm32·单片机·mcu·嵌入式实时数据库
wljy113 小时前
牛客每日一题(2026.4.30) 整数域二分
c语言·c++·算法·蓝桥杯·二分