鏈式棧是一種數據存儲結構,可以通過單鏈表的方式來實現,使用鏈式棧的優點在于它能夠克服用數組實現的順序棧空間利用率不高的特點,但是需要為每個棧元素分配額外的指針空間用來存放指針域。
頭文件 LinkStack.h
#ifndef __LINKSTACK_H__
#define __LINKSTACK_H__
#include "error.h"#define FALSE 0
#define TRUE 1typedef int StackData;
typedef struct _node
{StackData data;struct _node* next;
}Node;
typedef struct _linkStack
{Node* top;
}LinkStack;// 創建棧
LinkStack* Create_Stack ();// 判棧空否
int StackEmpty (LinkStack* s);// 進棧
int Push (LinkStack* s, StackData x);// 出棧
int Pop (LinkStack* s, StackData *x);// 獲取棧頂元素
int GetTop (LinkStack* s, StackData *x);// 銷毀表
int Destroy (LinkStack* s);#endif // __LINKSTACK_H__
源文件 LinkStack.c
#include "LinkStack.h"
#include <stdlib.h>// 創建棧
LinkStack* Create_Stack ()
{LinkStack* s = (LinkStack*) malloc(sizeof(LinkStack)/sizeof(char));if (NULL == s){errno = MALLOC_ERROR;return NULL;}// 置空棧s->top = NULL;return s;
}// 判棧空否
int StackEmpty (LinkStack* s)
{if (NULL == s){errno = ERROR;return FALSE;}return s->top == NULL;
}// 進棧
int Push (LinkStack* s, StackData x)
{if (NULL == s){errno = ERROR;return FALSE;}// 新建結點Node* node = (Node*) malloc(sizeof(Node)/sizeof(char));if (NULL == node){errno = MALLOC_ERROR;return FALSE;}node->data = x;node->next = s->top;s->top = node;return TRUE;
}// 出棧
int Pop (LinkStack* s, StackData *x)
{if (NULL == s){errno = ERROR;return FALSE;}if (StackEmpty(s)){errno = EMPTY_STACK;return FALSE;}Node* p = s->top;*x = p->data;s->top = p->next;free(p);return TRUE;
}// 獲取棧頂元素
int GetTop (LinkStack* s, StackData* x)
{if (NULL == s){errno = ERROR;return FALSE;}if (StackEmpty(s)){errno = EMPTY_STACK;return FALSE;}*x = s->top->data;return TRUE;
}// 銷毀棧
int Destroy (LinkStack* s)
{if (NULL == s){errno = ERROR;return FALSE;}int x;while (TRUE != StackEmpty(s)){Pop (s, &x);}free(s);return TRUE;
}