一.静态栈。
1.栈是一种后进先出的数据结构。2.栈规定只能在一端进行插入和删除。类似于用一个小桶装小球,最后装进去的那个小球是第一个被拿出来的,如果想要拿第一个装进去的小球,就要将除第一个小球外的所有小球先拿出来才能拿到第一个小球。
栈的建立(入栈)
由于栈是后进先出的类型,因此我们需要先定义一个栈顶top,且令top=0;然后建立一个数组来储存栈内的数据。例如向栈内存入n个数据的代码如下(入栈):
1.使用数组入栈:
int top=0,n,i;
int a[100];
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&a[top++]);
2.使用结构体入栈:
struct node{
int date[100];
int top;
}s;
int main()
{
int n,i;
s.top =0; //初始化栈为空
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&s.date[s.top ++]);
2
栈的输出(出栈).
输出栈中的n个数据:
1.使用数组出栈:
top=0;
for(i=1;i<=n;i++)
printf("%d ",a[top++]);
2.使用结构体出栈:
s.top =0;
for(i=1;i<=n;i++)
printf("%d ",s.date [s.top ++]);
二.动态栈(链栈)
顾名思义,就是将栈中的数据用链表储存。首先定义一个结构体来存链表的结点
struct node{
int date;
struct node *next;
}s;
然后定义栈顶并使栈顶为空
struct node *top;
top=NULL;
链栈的入栈
向链栈中输入n个数据:struct node *creat(int n,struct node *top) //入栈
{
int x,i;
struct node *p;
for(i=1;i<=n;i++)
{
scanf("%d",&x);
p=(struct node *)malloc(sizeof(struct node));
p->date =x;
p->next =top;
top=p;
}
return top;
}
链栈的出栈
struct node *creat2(struct node *top,int n) //出栈
{
if(top==NULL)
return 0;
struct node *p;
p=top;
top=top->next ;
free(p);
}
大概就这些了吧。。。。