當前位置: 首頁>>數據結構>>正文


棧的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/zh-tw/article/50.html,未經允許,請勿轉載。