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

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

 

  完整实现代码如下:

  #include "arith.h"

  int Arith_max(int x, int y) {

  return x > y x : y;

  }

  int Arith_min(int x, int y) {

  return x > y y : x;

  }

  int Arith_div(int x, int y) {

  if (-13/5 == -2

  && (x < 0) != (y < 0) && x%y != 0)

  return x/y - 1;

  else

  return x/y;

  }

  int Arith_mod(int x, int y) {

  if (-13/5 == -2

  && (x < 0) != (y < 0) && x%y != 0)

  return x%y + y;

  else

  return x%y;

  }

  int Arith_floor(int x, int y) {

  return Arith_div(x, y);

  }

  int Arith_ceiling(int x, int y) {

  return Arith_div(x, y) + (x%y != 0);

  }

  arith.c

  抽象数据类型

  抽象数据类型(abstract data type,ADT)是一个定义了数据类型以及基于该类型值提供的各种操作的接口

  一个高级类型是抽象的,因为接口隐藏了它的表示细节,以免客户调用程序依赖这些细节。下面是一个抽象数据类型(ADT)的规范化例子--堆栈,它定义了该类型以及五种操作:

  #ifndef STACK_INCLUDED

  #define STACK_INCLUDED

  #define T Stack_T

  typedef struct T *T;

  extern T Stack_new (void);

  extern int Stack_empty(T stk);

  extern void Stack_push (T stk, void *x);

  extern void *Stack_pop (T stk);

  extern void Stack_free (T *stk);

  #undef T

  #endif

  stack.h

  实现

  包含相关头文件:

  #include

  #include "assert.h"

  #include "mem.h"

  #include "stack.h"

  #define T Stack_T

  Stack_T的内部是一个结构,该结构有个字段指向一个栈内指针的链表以及一个这些指针的计数:

  struct T {

  int count;

  struct elem {

  void *x;

  struct elem *link;

  } *head;

  };

  Stack_new分配并初始化一个新的T:

  T Stack_new(void) {

  T stk;

  NEW(stk);

  stk->count = 0;

  stk->head = NULL;

  return stk;

  }