双端队列(deque)数组实现

数据结构与算法分析——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;
}


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值