当前位置: 首页>>数据结构>>正文


栈的C语言实现(原创)

使用单链表实现的栈,源码用C语言编写,VC6.0编译,分为三个文件,cstack.h是栈的数据结构和函数接口声明,cstack.c是栈的函数的定义,main.c是栈的测试文件。

/*
* File: cstack.h
* Purpose: implementation of stack in c
* Author: puresky
*/

#ifndef _C_STACK_H
#define _C_STACK_H

typedef struct StackNodeStruct StackNode;
struct StackNodeStruct
{
      void *_data;
      struct StackNodeStruct *_next;
};

typedef struct StackStruct Stack;
struct StackStruct
{
      StackNode *_top;
      int _count;
};

Stack *stack_new();
void stack_free(Stack *st);
void stack_push(Stack *st, void *data);
void *stack_top(Stack *st);
void *stack_pop(Stack *st);
int stack_size(Stack *st);
int stack_empty(Stack *st);
#endif

 

/*
* File: cstack.c
* Purpose: implementation of stack in c
* Author: puresky
*/

#include <stdlib.h>
#include "cstack.h"

StackNode *stack_node_new(void *data)
{
      StackNode *stn = (StackNode *)malloc(sizeof(StackNode));
      stn->_data = data;
      stn->_next = NULL;
      return stn;
}
void stack_node_free(StackNode *stn)
{
      if(stn)
      {
            free(stn);
      }
}

Stack *stack_new()
{
      Stack *st = (Stack *)malloc(sizeof(Stack));
      st->_count = 0;
      st->_top = NULL;
      return st;
}
void stack_free(Stack *st)
{
      StackNode *stn;
      StackNode *iter;
      if(st)
      {
            iter = st->_top;
            while(iter)
            {
                  stn = iter;
                  iter = iter->_next;
                  stack_node_free(stn);
            }
      }
}

void stack_push(Stack *st, void *data)
{
      StackNode *stn = stack_node_new(data);
      stn->_next = st->_top;
      st->_top = stn;
      st->_count++;
}

void *stack_top(Stack *st)
{
      return st->_top->_data;
}

void *stack_pop(Stack *st)
{
      void *ret = NULL;
      StackNode *stn;
      if(st->_top)
      {
            ret = st->_top->_data;
            stn = st->_top;
            st->_top = st->_top->_next;
            stack_node_free(stn);
            st->_count--;
      }
     
      return ret;
}

int stack_size(Stack *st)
{
      return st->_count;
}

int stack_empty(Stack *st)
{
      if(st->_top == NULL)
            return 1;
      return 0;
}

/*
* File: main.c
* Purpose: To test the stack
* Author: puresky
*/

#include <stdio.h>
#include <stdlib.h>
#include "cstack.h"

int main(int argc, char **argv)
{
      int data;
      Stack *st = stack_new();
      stack_push(st, (void *)1);
      stack_push(st, (void *)3);
      stack_push(st, (void *)5);
      stack_pop(st);
      stack_push(st, (void *)7);
      stack_push(st, (void *)9);
      stack_push(st, (void *)11);
      printf("size:%d\n", stack_size(st));
      while(!stack_empty(st))
      {
            data = (int)stack_top(st);
            printf("%d\n", data);
            stack_pop(st);
      }
      stack_free(st);
     
      system("pause");
      return 0;
}
本文由《纯净天空》出品。文章地址: https://vimsky.com/article/50.html,未经允许,请勿转载。