编写函数,采用链式存储和顺序存储实现队列的初始化、入队、出队操作;
时间: 2023-04-30 18:01:40 浏览: 195
链式存储实现队列的初始化、入队、出队操作:
1. 队列的初始化:
```c++
typedef struct node{
int data;
struct node *next;
}Node;
typedef struct queue{
Node *front;
Node *rear;
}Queue;
void initQueue(Queue *q){
q->front = q->rear = (Node*)malloc(sizeof(Node));
q->front->next = NULL;
}
```
2. 入队操作:
```c++
void enQueue(Queue *q, int data){
Node *p = (Node*)malloc(sizeof(Node));
p->data = data;
p->next = NULL;
q->rear->next = p;
q->rear = p;
}
```
3. 出队操作:
```c++
int deQueue(Queue *q){
if(q->front == q->rear){
printf("队列为空!\n");
return -1;
}
Node *p = q->front->next;
int data = p->data;
q->front->next = p->next;
if(q->rear == p){
q->rear = q->front;
}
free(p);
return data;
}
```
顺序存储实现队列的初始化、入队、出队操作:
1. 队列的初始化:
```c++
#define MAXSIZE 100
typedef struct queue{
int data[MAXSIZE];
int front;
int rear;
}Queue;
void initQueue(Queue *q){
q->front = q->rear = 0;
}
```
2. 入队操作:
```c++
void enQueue(Queue *q, int data){
if((q->rear+1)%MAXSIZE == q->front){
printf("队列已满!\n");
return;
}
q->data[q->rear] = data;
q->rear = (q->rear+1)%MAXSIZE;
}
```
3. 出队操作:
```c++
int deQueue(Queue *q){
if(q->front == q->rear){
printf("队列为空!\n");
return -1;
}
int data = q->data[q->front];
q->front = (q->front+1)%MAXSIZE;
return data;
}
```
阅读全文