经典抽象数据类型 堆栈(笔记)

获取内存来存储值有三种方案:静态数组,动态分配的数组、动态分配的链式结构。

用静态数组实现堆栈:

#include "stack.h"

#include <assert.h>

#define STACK_SIZE 100

static STACK_TYPE      stack[STACK_SIZE];

static int       top_element = -1;

void push (STACK_TYPE value)

{

  assert(!is_full());

  top_element += 1;

  stack[top_element] = value;

}

void pop(void)

{

  assert(!is_empty());

  top_element -=1;

}

STACK_TYPE top(void)

{

  assert(!is_empty());

  return stack[top_element];

}

int is_empty(void)

{

  return top_element == -1;

}

int is_full(void)

{

  return top_element == STACK_SIZE -1;

}

------------------------

用动态数组实现堆栈

#include "stack.h"

#include <stdio.h>

#include <studlib.h>

#include <malloc.h>

#include <assert.h>

static STACK_TYPE  *stack;

static size_t   stack_size;

static  int   top_element = 1;

void create_stack(size_t size)

{

  assert(stack_size == 0);

  stack_size = size;

  stack = malloc(stack_size *sizeof(STACK_TYPE));

  assert(stack != NULL);

}

void destroy_stack(void)

{

  assert (stack_size >0);

  stack_size = 0;

  free(stack);

  stack = NULL;

}

void push (STACK_TYPE value)

{

  assert(!is_full());

  top_element += 1;

  stack[top_element] = value;

}

void pop(void)

{

  assert(!is_empty());

  top_element -=1;

}

STACK_TYPE top(void)

{

  assert(!is_empty());

  return stack[top_element];

}

int is_empty(void)

{

  assert(stack_size > 0);

  return top_element == -1;

}

int is_full(void)

{

  

  assert(stack_size > 0);

  return top_element == STACK_SIZE -1;

}

-------------

链表实现的堆栈

#include "stack.h"

#include <stdio.h>

#include <studlib.h>

#include <malloc.h>

#include <assert.h>

#define FALSE  0

typedef  struct  STACK_NODE

{

  STACK_TYPE  value;

  struct  STACK_NODE * next;

}StackNode;

static  StackNode * stack;//指向堆栈第一个节点的指针。

void create_stack (size_t size)

{

}  //一个空函数

void destroy_stack(void)

{

  while(! is_empty())

  pop();

}

void push(STACK_TYPE value)

{

  StackNode  *new_node;

  new_node = malloc(sizeof(StackNode));

  assert(new_node != NULL);

  new_node->value = value;

  new_node->next = stack;

  stack = new_node;

}

void pop(void)

{

  StackNode * first_node;

  assert(! is_empty());

  first_node = stack;

  stack = first_node->next;

  free(first_node);

}

STACK_TYPE  top(void)

{

  assert(!is_empty());

  return stack->value;

}

int is_empty(void)

{

  return stack == NULL;

}

int is_full(void)

{

  return FALSE;//不会填满。

}

posted on 2011-07-26 16:27  dusts  阅读(415)  评论(0编辑  收藏  举报

导航