数据结构之链式栈的一些基本操作

来源:互联网 发布:js数组去重方法 编辑:程序博客网 时间:2024/06/05 10:58

链式栈是一种数据存储结构,可以通过单链表的方式来实现,使用链式栈的优点在于它能够克服用数组实现的顺序栈空间利用率不高的特点,但是需要为每个栈元素分配额外的指针空间用来存放指针域。
头文件 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;}
原创粉丝点击