C语言接口与实现实例(五)

2014-07-19 23:04:09 · 作者: · 浏览: 192

 

  其中NEW是一个另一个接口中的一个分配宏指令。NEW(p)将分配该结构的一个实例,并将其指针赋给p,因此Stack_new中使用它就可以分配一个新的Stack_T

  当count=0时,Stack_empty返回1,否则返回0:

  int Stack_empty(T stk) {

  assert(stk);

  return stk->count == 0;

  }

  assert(stk)实现了可检查的运行期错误,它禁止空指针传给Stack中的任何函数。

  Stack_push和Stack_pop从stk->head所指向的链表的头部添加或移出元素:

  void Stack_push(T stk, void *x) {

  struct elem *t;

  assert(stk);

  NEW(t);

  t->x = x;

  t->link = stk->head;

  stk->head = t;

  stk->count++;

  }

  void *Stack_pop(T stk) {

  void *x;

  struct elem *t;

  assert(stk);

  assert(stk->count > 0);

  t = stk->head;

  stk->head = t->link;

  stk->count--;

  x = t->x;

  FREE(t);

  return x;

  }

  FREE是另一个接口中定义的释放宏指令,它释放指针参数所指向的空间,然后将参数设为空指针

  void Stack_free(T *stk) {

  struct elem *t, *u;

  assert(stk && *stk);

  for (t = (*stk)->head; t; t = u) {

  u = t->link;

  FREE(t);

  }

  FREE(*stk);

  }

  完整实现代码如下:

  #include

  #include "assert.h"

  #include "mem.h"

  #include "stack.h"

  #define T Stack_T

  struct T {

  int count;

  struct elem {

  void *x;

  struct elem *link;

  } *head;

  };

  T Stack_new(void) {

  T stk;

  NEW(stk);

  stk->count = 0;

  stk->head = NULL;

  return stk;

  }

  int Stack_empty(T stk) {

  assert(stk);

  return stk->count == 0;

  }

  void Stack_push(T stk, void *x) {

  struct elem *t;

  assert(stk);

  NEW(t);

  t->x = x;

  t->link = stk->head;

  stk->head = t;

  stk->count++;

  }

  void *Stack_pop(T stk) {

  void *x;

  struct elem *t;

  assert(stk);

  assert(stk->count > 0);

  t = stk->head;

  stk->head = t->link;

  stk->count--;

  x = t->x;

  FREE(t);

  return x;

  }

  void Stack_free(T *stk) {

  struct elem *t, *u;

  assert(stk && *stk);

  for (t = (*stk)->head; t; t = u) {

  u = t->link;

  FREE(t);

  }

  FREE(*stk);

  }

  stack.c