数据结构学习之栈

数据结构学习之栈,第1张

数组加循环>>栈

栈先入后出(FILO)例子d 先压进的后打出

栈里面的数据可以是任意数据类型

入栈 向里面放数据

出栈 将数据从栈里取出

栈只有入栈和出栈的 *** 作

并且只能 *** 作最顶层的数据

/*
思路:
@创建一个容器 即数组
@放数据: 栈指针指向下一个位置 此时指向的数据为空 top++
@取数据: 将指针指向之前放入的数据 即--top
@检测数据是否为空:为空则结束取数据 

简洁版: 
//数据结构:栈
#include

char stack[512];//存放栈的数据
int top = 0;	//指向栈顶的指针

void push(char c);
char pop(void);
int is_empty(void);

int main(void) {
	push('a');
	push('b');
	while (!is_empty()) {
		putchar(pop());
	}
	return 0;
}

//入栈 *** 作
void push(char c) {
	stack[top++] = c;
}

//出栈 *** 作
int pop(void) {
	return stack[--top];
}

//检测栈是否为空
int is_empty(void) {
	return top == 0;
}
部分注释版本:
//数据结构:栈
#include

char stack[512];//存放栈的数据
int top = 0;		//指向栈顶的指针

void push(char c);
char pop(void);
int is_empty(void);

int main(void) {
	push('a');
	push('b');
	while (!is_empty()) {  //一直检测栈是否为空 为空则退出  is_empty() == 0与!is_empty()作用相同		
		putchar(pop());
	}
	return 0;
}

//入栈 *** 作
void push(char c) {
	//存放数据后指向下一个位置 top++是先使用top 使用完++
	stack[top++] = c;
}

//出栈 *** 作
char pop(void) {
	//取出数据指向前一个数据 --top是先减一在使用数据
	return stack[--top];
}

//检测栈是否为空
int is_empty(void) {
	//top为零返回真 不为零则为假 真即为空,假即为不空
	return top == 0;
}
全注释版本:方便复习
//数据结构:栈
#include

char stack[512];//存放栈的数据
int top = 0;		//指向栈顶的指针

void push(char c);
int pop(void);
int is_empty(void);

int main(void) {
	push('a');//放字符a
	push('b');//放字符b
	while (!is_empty()) { //一直检测栈是否为空 为空则退出is_empty() == 0与!is_empty()作用相同
		putchar(pop());//将栈中的数据打印
	}
	return 0;
}

//入栈 *** 作
void push(char c) {
	//存放数据后指向下一个位置 top++是先使用top 使用完++
	stack[top++] = c;
}

//出栈 *** 作
char pop(void) {
	//取出数据指向前一个数据 --top是先减一在使用数据
	return stack[--top];
}

//检测栈是否为空
int is_empty(void) {
	/*	if (top == 0) {
			return 1;	//返回为真
		}
		if (top == 0) {
			return 0;	//返回为假
		}
	*/
	//top为零返回真 不为零则为假 真即为空,假即为不空
	return top == 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/727974.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-26
下一篇2022-04-26

发表评论

登录后才能评论

评论列表(0条)

    保存