C实现一个简单链栈

来源:互联网 发布:手机可以plc编程软件吗 编辑:程序博客网 时间:2024/05/21 11:32

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

#include<stdio.h>#include<stdlib.h>#define ElemType inttypedef struct Ls{    ElemType data;    struct Ls *next;}Node;Node *creatstack();                 //creat a empty stackvoid pushstack(ElemType,Node **);   //sent data to stackElemType popstack(Node **);         //let data popvoid display(Node **);              //print all dataint emptyjudge(Node **);            //judge if it is a empty stackint 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;}
0 0
原创粉丝点击