双端队列(deque)数组实现
2016-04-01 12:43
459 查看
数据结构与算法分析——c语言描述 练习3.26 答案
很水的题。终于把第三章的课后习题答案写完了,还是有点小激动的。
deque.h
deque.c
很水的题。终于把第三章的课后习题答案写完了,还是有点小激动的。
deque.h
typedef int ElementType; #ifndef _Queue_h #define _Queue_h struct DequeRecord; typedef struct DequeRecord *Deque; int isEmpty(Deque q); int isFull(Deque q); Deque createDeque(int maxElements); void disposeDeque(Deque q); void makeEmpty(Deque q); void Push(ElementType X, Deque D); ElementType Pop(Deque D); void Inject(ElementType X, Deque D); ElementType Eject(Deque D); #endif
deque.c
#include"deque.h" #include"fatal.h" #include<stdlib.h> #define MinQueueSize (5) struct DequeRecord { int capacity; int front; int rear; int size; ElementType *array; }; int isEmpty(Deque q) { return q->size == 0; } int isFull(Deque q) { return q->size == q->capacity; } Deque createDeque(int maxElements) { if (maxElements < MinQueueSize) Error("Queue size is too small"); Deque q = malloc(sizeof(struct DequeRecord)); if (q == NULL) Error("out of memory"); q->array = malloc(maxElements*sizeof(ElementType)); if (q->array == NULL) Error("out of memory"); q->capacity = maxElements; makeEmpty(q); return q; } void makeEmpty(Deque q) { q->size = 0; q->front = 1;//这个是重点啊,当增加一个元素之后,rear和front同时都是1 q->rear = 0; } void Push(ElementType X, Deque D) { if (isFull(D)) Error("out of space"); D->front = (D->front - 1 + D->capacity) % D->capacity; D->array[D->front]=X; D->size++; } ElementType Pop(Deque D) { if (isEmpty(D)) { Error("empty deuqe"); } ElementType x = D->array[D->front]; D->front = (D->front+ 1 + D->capacity) % D->capacity; D->size--; return x; } void Inject(ElementType X, Deque D) { if (isFull(D)) Error("out of space"); D->rear = (D->rear + 1 + D->capacity) % D->capacity; D->array[D->rear]=X; D->size++; } ElementType Eject(Deque D) { if (isEmpty(D)) { Error("empty deuqe"); } ElementType x = D->array[D->rear]; D->rear = (D->rear - 1 + D->capacity) % D->capacity; D->size--; return x; }
相关文章推荐
- EasyUi的tab组件href属性链接的页面JS代码无法执行
- UnCaught TypeError:date.getFullYear is not a function解决方案
- 前台框架EasyUI的弹出框dialog,样式调整总结
- 快速排序法QuickSort
- Bluetooth4.3 读取特征字值的问题
- UITableView API大百科
- iOS学习笔记之UITableView之右侧索引
- Xcode报错: does not contain bitcode. You must rebuild it with bitcode enabled
- String,StringBuffer与StringBuilder的区别??
- ios 中请求主线程刷新UI
- String,StringBuffer, StringBuilder 的区别是什么?
- 图形用户界面(GUI)
- 图形用户界面(GUI)
- afnetwork 又一个坑“The request timed out”
- EasyUi combotree 实现动态加载树节点
- php require和include区别
- UITableview性能优化总结
- datatables(1.10.10+)+模块化请求(require.js or others)
- EasyUi中的Combogrid 实现分页和动态搜索远程数据
- currval of sequence "follow_id_seq" is not yet defined in this session