链栈是用类似于链表的形式实现的栈。
作为一个记录吧,写的不好之处还望指出。
#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;
}