C实现一个简单链栈

链栈是用类似于链表的形式实现的栈。
作为一个记录吧,写的不好之处还望指出。

#include<stdio.h>
#include<stdlib.h>
#define ElemType int

typedef struct Ls
{
    ElemType data;
    struct Ls *next;
}Node;

Node *creatstack();                 //creat a empty stack
void pushstack(ElemType,Node **);   //sent data to stack
ElemType popstack(Node **);         //let data pop
void display(Node **);              //print all data
int emptyjudge(Node **);            //judge if it is a empty stack

int main(void)
{
    //beacuse s must link to top of stack,in popstack()
    //we need change it,when nember of Node added or reduced
    //but we cannot return it because we need Elemtype
    //so we use **s
    Node **s,*base;
    int i,t;
    *s=creatstack();
    base=*s;
    printf("--the stack has created\n");
    printf("--1:push stack\n--2.pop stack\n--3.display stack\n");
    while(1)
    {   
        printf("--over!\n--choice:");
        scanf("%d",&i);
        switch(i)
        {
            case 1:printf("--data:");scanf("%d",&t);pushstack(t,s);break;
            case 2:
                {
                    if(emptyjudge(s))
                        printf("--%d leave stack.\n",popstack(s));
                    else
                        printf("--stack has been empty.\n");
                    break;
                }
            case 3:display(s);break;
            default:printf("error,try again\n");
        }
    }
}

int emptyjudge(Node **s)
{
    if((*s)->next==NULL)
        return 0;
    else
        return 1;
}

Node *creatstack()
{
    Node *te;
    te=(Node *)malloc(sizeof(Node));
    te->next=NULL;
    return te;
}

void pushstack(ElemType e,Node **s)
{
    Node *temp;
    temp=*s;
    *s=(Node *)malloc(sizeof(Node));
    (*s)->next=temp;
    (*s)->data=e;
}

ElemType popstack(Node **s)
{
    int i=(*s)->data;
    (*s)=(*s)->next;
    return i;
}

void display(Node **s)
{
    Node *temp=*s;
    while(emptyjudge(s))
    {
        printf("--%5d--\n",(*s)->data);
        (*s)=(*s)->next;
    }
    *s=temp;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值