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

#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;
    }
}

 

posted @ 2013-08-30 08:53  yexuannan  阅读(943)  评论(0编辑  收藏  举报