栈,也是一种表结构,特点是先进后出。实现方式也有两种:数组和链表。本文主要是复习,老鸟跳过!具体主要包括以下操作:
Stack CreateStack(void);
int IsEmpty(Stack s);
//int IsFull(Stack s);//链式stack可以不断申请space
void MakeEmpty(Stack s);
ElementType Pop(Stack s);
ElementType Top(Stack s);
void Push(ElementType e,Stack s);
void Print(Stack s);
一、创建stack
以链式结构为例,先新建一个空的stack,也就是新建一个表头节点(好处在于插入和删除操作更方便)。示例代码如下:
// 创建stack
Stack CreateStack(void){
Stack s;//带表头
//s=malloc(sizeof(Stack));//error!,just allocal 4 bits for pointer
s=malloc(sizeof(struct Node));
if(s==NULL){
printf("out of space!");
}else{
s->next=NULL;
MakeEmpty(s);
}
return s;
}
二、入栈操作,对应于Push函数。主要是将元素压入栈中。示例代码如下:
//push
void Push(ElementType e,Stack s){
ptrToNode tmp;
tmp=malloc(sizeof(struct Node));
if(tmp!=NULL){
tmp->e=e;
tmp->next = s->next;
s->next = tmp;
}else{
printf("error:out of space!");
}
}
三、出栈操作,对应于Pop函数,主要是将栈顶元素弹出。示例代码如下:
//pop
ElementType Pop(Stack s){
ptrToNode tmp;
ElementType e;
if(!IsEmpty(s)){
tmp = s->next;
s->next=s->next->next;
e = tmp->e;
free(tmp);
}else{
printf("stack is empty!");
}
return e;
}
四、判断栈是否为空。也就是链表是否为空。示例代码如下:
//判断是否为空
int IsEmpty(Stack s){
return s->next==NULL;
}