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;
}
相关推荐
LaoWaiHang2 小时前
C语言从头学61——学习头文件signal.h
c语言
一名路过的小码农2 小时前
C/C++动态库函数导出 windows
c语言·开发语言·c++
m0_631270402 小时前
标准c语言(一)
c语言·开发语言·算法
万河归海4282 小时前
C语言——二分法搜索数组中特定元素并返回下标
c语言·开发语言·数据结构·经验分享·笔记·算法·visualstudio
小周的C语言学习笔记2 小时前
鹏哥C语言36-37---循环/分支语句练习(折半查找算法)
c语言·算法·visual studio
凌肖战3 小时前
力扣上刷题之C语言实现(数组)
c语言·算法·leetcode
Jhxbdks4 小时前
C语言中的一些小知识(二)
c语言·开发语言·笔记
代码雕刻家4 小时前
数据结构-3.1.栈的基本概念
c语言·开发语言·数据结构
AlexMercer10125 小时前
【C++】二、数据类型 (同C)
c语言·开发语言·数据结构·c++·笔记·算法
Reese_Cool5 小时前
【C语言二级考试】循环结构设计
android·java·c语言·开发语言