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