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

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

 

转载于:https://www.cnblogs.com/yexuannan/p/3290702.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值