用C语言写队列的链式存储结构的操作代码
时间: 2023-04-05 15:03:46 浏览: 129
队列的链式存储C语言实现
我可以回答这个问题。以下是用C语言写队列的链式存储结构的操作代码:
```
#include <stdio.h>
#include <stdlib.h>
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 = NULL;
}
int isQueueEmpty(Queue *q) {
return q->front == NULL;
}
void enQueue(Queue *q, int data) {
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (isQueueEmpty(q)) {
q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}
int deQueue(Queue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty.\n");
return -1;
}
int data = q->front->data;
Node *temp = q->front;
q->front = q->front->next;
free(temp);
return data;
}
void printQueue(Queue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty.\n");
return;
}
Node *temp = q->front;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Queue q;
initQueue(&q);
enQueue(&q, 1);
enQueue(&q, 2);
enQueue(&q, 3);
printQueue(&q);
printf("Dequeued element: %d\n", deQueue(&q));
printf("Dequeued element: %d\n", deQueue(&q));
printQueue(&q);
return 0;
}
```
阅读全文