定义
#define StackSize 6 //栈的元素个数
typedef struct node{//定义
int data;
struct node *next;
}StackNode;
实现代码
#include"stdio.h"
#include"stdlib.h"
#include"s.h"
void InitStack(StackNode **p){//初始化链栈,二级指针使改变地址有效返回
*p=NULL;
}
int EmptyStack(StackNode *p){
if(p==NULL)
return 1;
else
return 0;
}
void EnterStack(StackNode **top,int x){//进栈
StackNode *p=(StackNode*)malloc(sizeof(StackNode));//开辟节点空间
p->data =x;
p->next =*top;
*top=p;
}
int LeaveStack(StackNode **top){//出栈
int x;
StackNode *p;
p=*top;
x=p->data ;
*top=p->next ;
free(p);
return x;
}
main(){
StackNode *p;
int arr[]={1,2,3,4,5,6};
int i;
int x;
InitStack(&p);
for(i=0;i<StackSize;i++){//使元素逐一进栈
EnterStack(&p,arr[i]);
}
for(i=0;i<StackSize;i++){//输出栈元素
x=LeaveStack(&p);
printf("%d ",x);
}
system("pause");
}
应用二级指针是由于在函数的操作过程中需要对地址改变并返回,一级指针只能对元素进行操作,返回的值为有效