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;
}
相关推荐
gugucoding8 小时前
21. 【C语言】打包不同类型:结构体
c语言·开发语言
gugucoding9 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
czhaii14 小时前
串口1中断收发-C语言-MODBUS协议
c语言·开发语言
apihz14 小时前
随机驾考题目(C 照科一 / 科四 2000+ 题)免费API调用教程
android·java·c语言·开发语言·网络协议·tcp/ip
三十岁老牛再出发17 小时前
07.07.每日总结
c语言·windows·python
C++ 老炮儿的技术栈20 小时前
MFC 自定义纯色居中文字进度条控件
c语言·数据库·c++·windows·算法·c·visual studio
gugucoding21 小时前
34. 【C语言】性能优化意识启蒙
c语言·开发语言·性能优化
Drone_xjw1 天前
从 GDB 到 CDB:C/C++ 程序调试的两把“手术刀”
c语言·开发语言·c++
gugucoding2 天前
25. 【C语言】二进制文件与随机读写
c语言·开发语言
十月的皮皮2 天前
C语言学习笔记20260706-栈的压入、弹出序列验证
c语言·笔记·学习