采用链式存储实现,进栈、出栈操作

来源:互联网 发布:ue软件算法 编辑:程序博客网 时间:2024/06/08 08:17

#include<stdio.h>
#include<stdlib.h>

typedef struct stacklist{
 int data;
 struct stacklist *next;
}stacklist,*linkstack;

linkstack top,head;

linkstack create()
{
 linkstack p;
 p=(linkstack)malloc(sizeof(stacklist));
 p->next=NULL;
 return p;
}

void bulidstack()
{
 linkstack p,q;
 int data;
 p=top;
 printf("请输入进栈的元素:");
 scanf("%d",&data);
 q=create();
 q->data=data;
 q->next=p->next;
 top->next=q;
}

void outstack()//出栈

 linkstack p;
    p=top->next;
 if(p!=NULL)
 {
  printf("%d 出栈\n",p->data);
  top->next=p->next;
  free(p);
 }
 else
  printf("栈为空\n"); 
}

void tip()
{
 printf("**********\n");
 printf("*1 进栈  *\n");
 printf("*2 出栈  *\n");
 printf("*请选择:*\n");
 printf("**********\n");
}
int main()
{
 top=create();
 int k;
 tip();
 while(scanf("%d",&k),k)
 {
  switch(k)
  {
  case 1:
   bulidstack();
   printf("操作完成\n");
   tip();
   break;
  case 2:
   outstack();
   printf("操作完成\n");
   tip();
   break;
  }
 }
 return 0;
}

原创粉丝点击