特点:后进先出

栈的两种形式:数组栈和链式栈

下面我们来讲解这两种栈;

一.数组栈

首先定义数组栈(计算机不认识什么数组栈)

typedef struct{
int shuzu[10];
int top,base;
}zhan; (英文不好所所以用拼音代替)

1.置空栈(前面的定义就是简单的弄框架,一些细节还需要优化)

zhan->base = zhan->top = 0;

2.判断是否满栈

if(zhan->top-zhan->base == 9){
return 0;(0代表栈满了,注意zhan->top相当于盖子,所以占用一个数组位)
}
return 1;(1代表没满)

此处的自定义函数建议为int类型,方便使用;

3.入栈

zhan->shuzu[zhan->top] = number;

zhan->top++;(为下一次做准备);

4.出栈

 

do{
a->top--;
printf("%d",a->shuzu[a->top]);
}while(a->top!= 0);

下是完整的入栈9个数字的代码

#include <stdio.h> 
typedef struct{
	int shuzu[10];
	int top,base;
}zhan;
void zhikong(zhan *a){
	a->base = a->top = 0;
}
void ruzhan(zhan *a){
	int number;
	scanf("%d",&number);
	a->shuzu[a->top++] = number;
}
int panduan(zhan *a){
	if(a->top-a->base == 9){
		return 0;
	}
	return 1;
}
void chuzhan(zhan *a){
	if(a->top-a->base == 0){
		return ;
	}
	do{
		a->top--;
		printf("%d",a->shuzu[a->top]);
	}while(a->top!= 0);
}
int main(){
	zhan a;
	zhikong(&a);
	int i;
	for(i = 0; i < 9; i++){
		if(panduan(&a)){
			ruzhan(&a);
		}
	}
	chuzhan(&a);
}

 

二.链式栈

首先定义链式栈

typedef struct{
int shuzi;
    struct *next;
}zhan;(计算机也不认识什么链式栈)

1.创建top和base;(盖子和底部得弄出来)

       

zhan *top,
top = NULL;

 

(此时top,base相当于NULL)

2.入栈

zhan *b;
int i;
for(i = 0; i < 2; i++){   (此处的2的含义,如果你想要进两个栈就为2,以此类推......)
b = (zhan*)malloc(sizeof(zhan));
b->shuzi = i;
b->next = *top;
*top = b;
}

3.出栈

for(; top!= NULL; top = top->next){
printf("%d\n",top->shuzi);
}

链式栈比数组栈简单,不用判满。

以下是链式栈完整代码,用途是存数字

 

#include <stdio.h>
typedef struct node{
	int shuzi;
    struct node *next;
}zhan;
void ruzhan(zhan **top){
	zhan *b;
	int i;
	for(i = 0; i < 2; i++){
	b = (zhan*)malloc(sizeof(zhan));
	b->shuzi = i;
	b->next = *top;
	*top = b;	
	} 
}
void chuzhan (zhan *top){
	for(; top!= NULL; top = top->next){
		printf("%d\n",top->shuzi);
	}
}
int main(){
	zhan *top;
	top = NULL;
	ruzhan(&top);
	chuzhan(top);
}
到这里结束了。
以后还会不定时更新数据结构内容
感谢过程中帮助我的同学,我QQ1374487940,有需要帮助的同学可以加QQ询问

 

还有数据结构内容持续更新,欢迎加QQ1374487940,注明CSDN

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值