链栈即链式栈,也就是说我们不用再考虑空间的大小,可随心所欲的进行数据的插入/删除了。和顺序栈一样,仍然要保持其stack的特性,只在一端进行插入和删除,后进先出。
(2018-02-14 代码更新)
linkstack.h:
#ifndef __LINKSTACK_H_ #define __LINKSTACK_H_ #define bool int #define true 1 #define false 0 typedef int KeyType; typedef struct lstack { KeyType key; struct lstack * top; }Stack; Stack*CreateStack(); int IsEmpty(); bool Push(); bool Pop(); Stack*getTopNode(); KeyType getTop(); void Clear(); void Destroy(); #endif
linkstack.c:
/* linkstack.c */ #include <stdio.h> #include <stdlib.h> #include "linkstack.h" Stack*CreateStack(void) { Stack*s; s = (Stack*)malloc(sizeof(Stack)); s->top = NULL; return s; } int IsEmpty(Stack*s) { return s->top == NULL; } bool Push(Stack*s, KeyType Data) { Stack*p; if((p = (Stack*)malloc(sizeof(Stack))) == NULL) return false; p->key = Data; p->top = s->top; s->top = p; return true; } bool Pop(Stack*s) { Stack*p; if(IsEmpty(s)) return false; p = s->top; s->top = s->top->top; free(p); p = NULL; return true; } Stack*getTopNode(Stack*s) { return s->top; } KeyType getTop(Stack*s) { return getTopNode(s)->key; } void Clear(Stack*s) { while(!IsEmpty(s)) Pop(s); } void Destroy(Stack*s) { if(s != NULL) { Clear(s); if(s != NULL) free(s); s = NULL; } }