c语言

c语言列队有何数据结构

小樊
82
2024-10-16 22:47:34
栏目: 编程语言

在C语言中,实现队列这种数据结构,可以使用数组或链表。以下是使用这两种数据结构实现队列的示例:

方法一:使用数组

#include <stdio.h>
#include <stdlib.h>

#define SIZE 5

typedef struct {
    int data[SIZE];
    int front;
    int rear;
} Queue;

Queue q;

void initQueue() {
    q.front = q.rear = -1;
}

int isFull() {
    return (q.rear + 1) % SIZE == q.front;
}

int isEmpty() {
    return q.front == -1;
}

void enqueue(int item) {
    if (isFull()) {
        printf("Queue is full.\n");
        return;
    }
    if (isEmpty()) {
        q.front = q.rear = 0;
    } else {
        q.rear = (q.rear + 1) % SIZE;
    }
    q.data[q.rear] = item;
}

int dequeue() {
    if (isEmpty()) {
        printf("Queue is empty.\n");
        return -1;
    }
    int item = q.data[q.front];
    if (q.front == q.rear) {
        q.front = q.rear = -1;
    } else {
        q.front = (q.front + 1) % SIZE;
    }
    return item;
}

int main() {
    initQueue();
    enqueue(1);
    enqueue(2);
    enqueue(3);
    printf("Dequeued: %d\n", dequeue());
    printf("Dequeued: %d\n", dequeue());
    return 0;
}

方法二:使用链表

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* next;
} Node;

typedef struct {
    Node* front;
    Node* rear;
} Queue;

Queue* createQueue() {
    Queue* q = (Queue*)malloc(sizeof(Queue));
    q->front = q->rear = NULL;
    return q;
}

void initQueue(Queue* q) {
    q->front = q->rear = NULL;
}

int isFull(Queue* q) {
    return q->rear->next == NULL;
}

int isEmpty(Queue* q) {
    return q->front == NULL;
}

void enqueue(Queue* q, int item) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = item;
    newNode->next = NULL;
    if (isFull(q)) {
        printf("Queue is full.\n");
        return;
    }
    if (isEmpty(q)) {
        q->front = q->rear = newNode;
    } else {
        q->rear->next = newNode;
        q->rear = newNode;
    }
}

int dequeue(Queue* q) {
    if (isEmpty(q)) {
        printf("Queue is empty.\n");
        return -1;
    }
    Node* temp = q->front;
    int item = temp->data;
    q->front = q->front->next;
    if (q->front == NULL) {
        q->rear = NULL;
    }
    free(temp);
    return item;
}

int main() {
    Queue* q = createQueue();
    initQueue(q);
    enqueue(q, 1);
    enqueue(q, 2);
    enqueue(q, 3);
    printf("Dequeued: %d\n", dequeue(q));
    printf("Dequeued: %d\n", dequeue(q));
    return 0;
}

这两种方法都可以实现队列的基本操作,包括入队(enqueue)和出队(dequeue)。你可以根据自己的需求和场景选择合适的方法。

0
看了该问题的人还看了