天天看点

C语言实现基本数据结构之栈

#include <stdio.h>
#include <stdlib.h>
//定义一个栈
typedef struct anode{
           int data;
           struct node* next,*pro;
}node;
typedef struct astack{
           struct anode *bottom,*top;
}stack;

  stack* Create(stack *s){
    //创造一个栈
    s=(stack*)malloc(sizeof(stack));
    s->top=s->bottom = (node*)malloc(sizeof(node));
     return s;
  }

   void Insert(stack *s,int i){
      //结点入栈
        node *p = (node*)malloc(sizeof(node));
        p->data=i;
        s->bottom->next=p;
        p->pro=s->bottom;
        s->bottom=s->bottom->next;
   }
   //节点出栈
    void OutStack(stack *s){
       printf("%d",s->bottom->data);
        s->bottom=s->bottom->pro;
    }
  int main()
 {
     stack *s=NULL;
     s=Create(s);
    //节点入栈
     int n;
     scanf("%d",&n);
     int i=0;
     for(;i<n;i++){
            int num;
            scanf("%d",&num);
           Insert(s,num);
     }

    //节点出栈
    while(s->top!=s->bottom){
            OutStack(s);
    }
    return 0;
}