栈的链式存储结构称为链栈,它是运算受限的单链表, 插入和删除操作仅限制在表头位置上进行,栈顶指针就是链表的头指针。
链式栈的类型说明如下:
typedef struct node{
DataType data;
struct node *next
} LkStk;
LS->next==NULL为下溢条件,不考虑栈满(上溢)现象。
1. 初始化
void InitStack(LkStk *LS){
LS=(LkStk *)malloc(sizeof(LkStk));
LS->next=NULL;
}
2. 判断栈空
int EmptyStack(LkStk *LS){
if(LS->next == NULL) {
return 1
}else{
return 0;
}
}
3. 进栈
void Push (LkStk *LS, DataType x){
LkStk *temp;
temp= (LkStk *) malloc (sizeof (LkStk));
temp->data=x;
temp->next=LS->next;
LS->next=temp;
}
4. 出栈
int Pop (LkStk *LS){
LkStk *temp;
if (!EmptyStack (LS)){
temp=LS->next;
LS->next=temp->next;
free(temp);
return 1;
}else{
return 0;
}
}
5. 取栈顶元素
DataType GetTop(LkStk *LS){
if (!EmptyStack(LS)){
return LS->next->data;
}else{
return NULLData;
}
}
如果一个函数在完成之前又调用自身,则称之为递归函数。
例如:求整数n的阶乘函数
int func (int n){
if(n==0){
return(1)
}else{
return n*func (n-1)
};
}