用c语言并且使用链表实现队列
时间: 2024-05-20 13:17:53 浏览: 84
go语言通过数组和链表的方式实现队列 数组和链表.pdf
以下是使用链表实现队列的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 isEmpty(Queue *q) {
return q->front == NULL;
}
//入队操作
void enQueue(Queue *q, int data) {
Node *p = (Node*)malloc(sizeof(Node));
p->data = data;
p->next = NULL;
if (isEmpty(q)) {
q->front = q->rear = p;
} else {
q->rear->next = p;
q->rear = p;
}
}
//出队操作
int deQueue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return -1;
}
Node *p = q->front;
int data = p->data;
q->front = p->next;
if (q->front == NULL) q->rear = NULL;
free(p);
return data;
}
//输出队列中的所有元素
void printQueue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return;
}
printf("Queue: ");
Node *p = q->front;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Queue q;
initQueue(&q);
enQueue(&q, 1);
enQueue(&q, 2);
enQueue(&q, 3);
printQueue(&q);
printf("Dequeue: %d\n", deQueue(&q));
printQueue(&q);
enQueue(&q, 4);
printQueue(&q);
return 0;
}
阅读全文