栈除了可以有顺序实现以外,还可以有链栈
使用链式存储结构的栈
链栈一般没有头结点,头指针直接作为栈顶
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20 /* 存储空间初始分配量 */
typedef int Status;
typedef int ElemType;
typedef struct Node{
ElemType data;
struct Node * next;
}StackNode;
typedef struct {
StackNode * top;
int count;
}LinkStack;
//初始化一个空栈
Status InitStack(LinkStack *S){
S->top = NULL;
S->count = 0;
return OK;
}
//将一个栈清空
Status ClearStack(LinkStack *S){
StackNode * p = S->top;
StackNode * point2free;
while(p){
point2free = p;
p = p->next;
free(point2free);
}
S->count = 0;
return OK;
}
//判断栈是否为空
Status StackEmpty(LinkStack S){
if(S.count){
return FALSE;
}else{
return TRUE;
}
}
//获取栈的长度
int StackLength(LinkStack S){
return S.count;
}
//获取栈定元素的内容
Status GetTop(LinkStack S,ElemType *e){
StackNode *topNode = S.top;
if(topNode){
*e = topNode->data;
return OK;
}
return ERROR;
}
//入栈
Status Push(LinkStack *S,ElemType e){
StackNode * newNode = (StackNode*)malloc(sizeof(StackNode));
if(!newNode){
printf("creat push Node fail!\n");
return ERROR;
}
newNode->data = e;
newNode->next = S->top;//新节点指向栈顶
S->top = newNode;//重新定位栈顶
S->count++;
return OK;
}
//出栈
Status Pop(LinkStack *S,ElemType *e){
if(StackEmpty(*S)){
return ERROR;
}
StackNode *topNode = S->top;
*e = topNode->data;
S->top = topNode->next;
free(topNode);
S->count--;
return OK;
}
//打印栈
void PrintStack(LinkStack S){
printf("Stack start\n");
StackNode * curNode = S.top;
while(curNode){
printf("num = %d\n",curNode->data);
curNode = curNode->next;
}
printf("Stack end\n");
}
int main(){
LinkStack S;
InitStack(&S);
Push(&S,5);
Push(&S,4);
Push(&S,3);
Push(&S,2);
Push(&S,1);
PrintStack(S);
ElemType temp;
Pop(&S,&temp);
PrintStack(S);
return 0;
}