数据结构与算法分析——c语言描述 练习3.26 答案
很水的题。终于把第三章的课后习题答案写完了,还是有点小激动的。
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;
}