您的位置:首页 > 其它

链栈中的入栈操作有点类似于头插法

2013-08-30 08:53 113 查看
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(linkstack)
typedef struct node
{
int data;
struct node *next;
}linkstack;

linkstack *push(linkstack *top,int x);
linkstack *pop(linkstack *top,int *datap);
void print(linkstack *top);
int  menu_select();
void main()
{
linkstack *top=(struct node*)malloc(LEN);
top=NULL;
int kk,x; int *datap=(int *)malloc(sizeof(int *));
kk=menu_select();
do
{    switch(kk)
{
case 1: printf("请输入数据:");scanf("%d",&x); getchar();top=push(top, x);break;
case 2: top=pop(top,datap);break;
case 3: print(top);break;
case 0: return;
}
kk=menu_select();
}while(kk!=0);
}

linkstack *push(linkstack *top,int x)  //入栈操作
{
linkstack *p;
p=(struct node *)malloc(LEN);
p->data=x;
p->next=top;
top=p;
return(top);
}

linkstack *pop(linkstack *top,int *datap)
{
linkstack *p;
if(top==NULL)
{
printf("栈空!");
return(NULL);
}
else
{
*datap=top->data;
p=top;
top=top->next;
free(p);
return(top);
}
}

int menu_select()
{
char c;
int n;
printf("\n\t\t\t\t请选择操作\n");
printf("\t\t\t\t1:进栈运算\n");
printf("\t\t\t\t2:出栈运算\n");
printf("\t\t\t\t3:打印\n");
printf("\t\t\t\t0:退出\n");
do
{
c=getchar();
n=c-48;
}while((n>3)&&(n<0));
getchar();
return(n);
}

void print(linkstack *top)
{
linkstack *t;
t=top;
while(t!=NULL)
{
printf("%d\t",t->data);
t=t->next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: