我需要一段用两个类来实现双端队列的c++代码
时间: 2024-06-10 13:08:59 浏览: 96
当然,我很乐意为您提供这段代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
typedef struct {
int data[MAXSIZE];
int front;
int rear;
} Deque;
void initDeque(Deque *q) {
q->front = q->rear = MAXSIZE / 2;
}
int isFull(Deque *q) {
return (q->rear + 1) % MAXSIZE == q->front;
}
int isEmpty(Deque *q) {
return q->front == q->rear;
}
void addFront(Deque *q, int x) {
if (isFull(q)) {
printf("Deque is full!\n");
exit(1);
}
q->front = (q->front - 1 + MAXSIZE) % MAXSIZE;
q->data[q->front] = x;
}
void addRear(Deque *q, int x) {
if (isFull(q)) {
printf("Deque is full!\n");
exit(1);
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAXSIZE;
}
int deleteFront(Deque *q) {
if (isEmpty(q)) {
printf("Deque is empty!\n");
exit(1);
}
int x = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return x;
}
int deleteRear(Deque *q) {
if (isEmpty(q)) {
printf("Deque is empty!\n");
exit(1);
}
q->rear = (q->rear - 1 + MAXSIZE) % MAXSIZE;
return q->data[q->rear];
}
int main() {
Deque q;
initDeque(&q);
addFront(&q, 1);
addFront(&q, 2);
addRear(&q, 3);
printf("%d ", deleteFront(&q));
printf("%d ", deleteFront(&q));
printf("%d ", deleteRear(&q));
return 0;
}
```
希望这段代码对您有所帮助!
阅读全文