链栈的操作

#include <stdio.h>
#include <stdlib.h>
typedef struct linkstackstruct{
   int data;
   struct linkstackstruct *next;
}linkstack,*linkstacks;
//linkstacks top;
struct linkstackstruct *init()
{
   struct linkstackstruct *head;

   head=(linkstack *)malloc(sizeof(linkstack));
   if(head==NULL)
   {
   printf("error\n");
   exit (0);
   }
   else
   {
   head->next=NULL;

//    printf("ok\n");
   return head;
   }
}
struct linkstackstruct *push(linkstacks top,int number)
{
   linkstacks new;
   new =(linkstack* )malloc(sizeof(linkstack));
   new->data=number;
   new->next=top;
   top=new;
   printf("%d has insert.\n",number);
   return top;
}
struct linkstackstruct * pop(linkstacks top)
{
   struct linkstackstruct *p;
   p=top;
   top=top->next;
   int x;
   x=p->data;
   free(p);
   printf("%d has out\n",x);    
   return top;
}
void print(linkstacks top)
{
   linkstacks temp;
   temp=top;
   int d;
   while(temp->next !=NULL)
   {
   d=temp->data;
   printf("%d\n",d);
   temp=temp->next;
   }
}
int length(linkstacks ls)
{
   int leng=0;
   linkstacks ll;
   ll=ls;
   while(ll->next !=NULL)
   {
   ll=ll->next;
   ++leng;
   }
   return leng;
}
main()
{
   struct linkstackstruct *ls;
   ls=init();
   ls=push(ls,21);
   ls=push(ls,12);
   ls=push(ls,56);
   ls=push(ls,99);
   ls=push(ls,34);
   printf("the init stack:\n");
   print(ls);
   int len;
   len=length(ls);
   printf("the length of the stack is :%d \n",len);
   printf("element out:\n");
   ls=pop(ls);
   ls=pop(ls);
   printf("the stack after out:\n");
   print(ls);
}

你可能感兴趣的:(操作,栈,链栈)