栈的实现

来源:互联网 发布:淘宝上的色情杂志 编辑:程序博客网 时间:2024/03/29 17:50

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct stack
{
 int data;
 struct stack *next;
}STA;
//建立栈
STA *creatstack()
{
 STA *chead,*clast,*cnew;
 chead=(STA *)malloc(sizeof(STA));
 chead->next=NULL;
 clast=chead;
 cnew=(STA *)malloc(sizeof(STA));
 scanf("%d",&cnew->data);
 while(cnew->data)
 {
  cnew->next=clast->next;
  clast->next=cnew;
  cnew=(STA *)malloc(sizeof(STA));
  scanf("%d",&cnew->data);
 }
 free(cnew);
 return chead;
}
//建立空栈
STA *initstack()
{
 STA *head;
 head=(STA *)malloc(sizeof(STA));
 head->next=NULL;
 return head;
}
//返回栈顶元素
int gettop(STA *head)
{
 int e;STA *top;
 top=head->next;
 if(!top) exit(0);
 e=top->data;
 return e;
}
//向栈顶插入新元素
STA *push(STA *head,int e)
{
 STA *top,*pnew;
 pnew=(STA *)malloc(sizeof(STA));
 pnew->data=e;
 top=head->next;
 pnew->next=top;
 head->next=pnew;
 return head;
}
//删除栈顶元素,并返回其值
int pop(STA *head)
{
 STA *top;int e;
 top=head->next;
 if(!top) exit(0);
 e=top->data;
 head->next=top->next;
 return e;
}
//输出栈
void printstack(STA *head)
{
 STA *ph;
 ph=head->next;
 while(ph)
 {
  printf("%4d",ph->data);
  ph=ph->next;
 }
 printf("/n");
}
//返回栈顶元素
void gstack()
{
 STA *gh;
 printf("请先建立一个新栈:");
 gh=creatstack();
 printf("栈顶数据是:%d/n",gettop(gh));
}
//向栈顶插入新元素
void istack()
{
 STA *ih;int data;
 printf("请先建立一个新栈:");
 ih=creatstack();
 printf("请键入您要插入的数据:");
 scanf("%d",&data);
 ih=push(ih,data);
 printf("现在的栈如下:/n");
 printstack(ih);
}
//删除栈顶元素,并返回其值
void dstack()
{
 STA *dh;
 printf("请先建立一个新栈:");
 dh=creatstack();
 printf("您输入的栈如下:/n");
 printstack(dh);
 printf("被删除的栈顶元素是:%d/n",pop(dh));
 printf("现在的栈中数据如下:/n");
 printstack(dh);
}
/*菜单*/
void mmenu()
{
 printf("***——————主菜单——————***/n");
 printf("1.输出栈顶数据/n");
 printf("2.向栈中插入新数据/n");
 printf("3.删除栈顶数据/n");
 printf("0.退出该程序/n");
 printf("***———————————————***/n");
 printf("/n");
 printf("***——————请注意——————***/n");
 printf("1.本程序只能输入数字,按数字/"0/"来结束输入!/n");
 printf("2.严格按照所要求的格式操作!/n");
 printf("***———————————————***/n");
}
/*选择*/
void mchoice()
{
 int ch;
 printf("请键入主菜单中相应数字,选择相应操作:");
 scanf("%d",&ch);
 switch(ch)
 {
 case 1:gstack();break;
 case 2:istack();break;
 case 3:dstack();break;
 case 0:exit(0);
 default:printf("请键入相应数字进行选择!/n");
 }
}
void main()
{
 while(1)
 {
  system("cls");
  mmenu();
  mchoice();
  system("pause");
 }
}