一.静态栈。

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);
 }

大概就这些了吧。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值