干货4:链式栈

来源:互联网 发布:阿里云cdn添加域名 编辑:程序博客网 时间:2024/05/19 22:52
#include <stdlib.h>#include <stdio.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(){LinkStack* s = (LinkStack*)malloc(sizeof(LinkStack)/sizeof(char));if (s == NULL){errno = MALLOC_ERROR;return NULL;}// 置空栈s->top = NULL;return s;}// 判断空栈int StackEmpty (LinkStack *s){if (s == NULL){errno = ERROR;return FALSE;}return s->top == NULL;}// 进栈int Push (LinkStack *s, StackData x){if (s == NULL){errno = ERROR;return FALSE;}// 新建结点Node* node = (Node*)malloc(sizeof(Node)/sizeof(char));if (node == NULL){errno = MALLOC_ERROR;return FALSE;}node->data = x;node->next = s->top;s->top = node;return TRUE;}// 出栈int Pop (LinkStack *s, StackData *x){if (s == NULL){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 (s == NULL){errno = ERROR;return FALSE;}if (StackEmpty(s)){errno = EMPTY_STACK;return FALSE;}*x = s->top->data;return TRUE;}// 销毁栈int Destroy(LinkStack *s){if (s == NULL){errno = ERROR;return FALSE;}int x;while(StackEmpty(s) != TRUE){Pop (s, &x);}free(s);return TRUE;}

原创粉丝点击