栈的实现-简明易懂的2种方

本文写于本人小白入门之时,开始时举步难行,找了不少度娘、博客仍觉得不明确,走了许多的弯路,终于掌握了一些皮毛之见。自我总结了一些东西,个人认为是比较容易理解,以供大伙和个人学习,若有不正确之处恳请各位大神指出!

栈(Stack)的结构是“先进后出”,就像搭积木一样从上面一个一个的放下来,要拿回出来就要从上面一个一个拿回出来,不能直接从最下面拿,否则积木就会坍塌。

对于栈的建立个人按思想方式分为2大种派别:

一:数组实现

这种方法重点就是栈的top→我们用数组s[0]来代替,用s[0]来指向读数据该读到哪里了
#include<stdio.h>
#define max 100
int stackempty(int s[])
{
	if(s[0]==0)
		return 1;
	else 
		return 0;
}
int push(int s[],int x)
{
	if(s[0]==max-1)
		return -1;
	else
	{
		s[0]++;
		s[s[0]]=x;
		return 1;
	}
}
int pop(int s[])
{
	if(s[0]==0)
		return -1;
	else
	{
		s[0]--;
		return s[s[0]+1];
	}
}
void ifempty(int s[])
{
	int n=0;
	n=stackempty(s);
	if(n==1)
		printf("栈空!\n");
	else
		printf("栈非空!\n");
}	
int main()
{	
	int s[max],x;
	s[0]=0;
	ifempty(s);
	push(s,4);
	push(s,2);
	printf("已入栈\n");
	ifempty(s);
	printf("出栈:%d\n",pop(s));
	return 0;
}

二:指针传参实现

比较传统的做法,各种书籍上面普遍都是以这种方法来做逻辑上简单明了

#include<stdio.h>
#define max 100
typedef struct stack
{
	int top;
	int key[max];
}stack;
int stackempty(stack s)
{
	if(s.top==0)
		return 1;
	else
		return 0;
}
void push(stack *p,int x)
{
	if(p->top==max-1)
		printf("Stack is full!\n");
	else
	{
		p->key[p->top]=x;
		p->top++;
	}
}
void pop(stack *p)
{
	if(p->top==0)
		printf("Stack is empty!\n");
	else
	{
		p->top--;
		printf("%d\n",p->key[p->top]);
		
	}
}
void ifempty(stack s)
{
	if(stackempty(s)==1)
		printf("Stack is empty!\nYou can creat stack!\n");
	else
		printf("Stack is not empty!\n");
}
int main()
{
	stack s;
	s.top=0;
	ifempty(s);
	push(&s,2);
	push(&s,8);
    pop(&s);
	pop(&s);
	ifempty(s);
	return 0;
}
下面为栈的图示:

                         


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值