/*
* 链队,使用虚拟头节点
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int e;
struct Node *next;
} *Node; // struct Node* -> Node
typedef struct LinkedQueue {
Node dummyHead; // 使用虚拟头节点
Node tail;
int size;
} *LinkedQueue; // struct LinkedQueue* -> LinkedQueue
// 初始化
LinkedQueue initiation() {
LinkedQueue queue = (LinkedQueue) malloc(sizeof (struct LinkedQueue));
queue->size = 0;
queue->tail = NULL;
queue->dummyHead = (Node) malloc(sizeof (struct Node));
if (queue == NULL || queue->dummyHead == NULL) {
perror("LinkedQueue initiation failed");
exit(-1);
}
return queue;
}
// 获取队列大小
int getSize(LinkedQueue q) {
return q->size;
}
// 判断队列是否空
int isEmpty(LinkedQueue q) {
return q->size == 0;
}
// 入队
void enqueue(int e, LinkedQueue q) {
if (q->tail == NULL) {
q->tail = (Node) malloc(sizeof (struct Node));
q->tail->e = e;
q->tail->next = NULL;
q->dummyHead->next = q->tail;
} else {
Node new = (Node) malloc(sizeof(struct Node));
new->e = e;
new->next = q->tail->next;
q->tail->next = new;
q->tail = new;
}
q->size++;
}
// 出队
int dequeue(LinkedQueue q) {
if (isEmpty(q)) {
perror("Dequeue failed, the queue is empty now");
return -1;
}
int ret = q->dummyHead->next->e;
Node del = q->dummyHead->next;
q->dummyHead->next = del->next;
del->next = NULL;
free(del);
del = NULL;
q->size--;
if (q->dummyHead->next == NULL) {
q->tail = NULL;
}
return ret;
}
// 查看队首
int getFront(LinkedQueue q) {
if (isEmpty(q)) {
perror("GetFront failed, the queue is empty now");
return -1;
}
return q->dummyHead->next->e;
}
// 打印队列
void tostring(LinkedQueue q) {
printf("LinkedQueue: size = %d\n", q->size);
printf("front ");
Node cur = q->dummyHead->next;
while (cur != NULL) {
printf("%d->", cur->e);
cur = cur->next;
}
printf("NULL tail\n");
}
// 销毁队列
void destroy(LinkedQueue q) {
Node cur = q->dummyHead;
while (cur != NULL) {
cur = cur->next;
free(q->dummyHead);
q->dummyHead = cur;
}
q->tail = NULL;
if (q->dummyHead == NULL && q->tail == NULL) {
free(q);
q = NULL;
if (q == NULL) {
printf("The linkedQueue has successfully been destroyed.\n");
} else {
perror("LinkedQueue destroy fail");
}
} else {
perror("LinkedQueue destroy fail");
}
}
int main() {
LinkedQueue q = initiation();
for (int i = 0; i < 10; i ++) {
enqueue(i, q);
tostring(q);
if (i % 3 == 2) {
dequeue(q);
tostring(q);
}
}
destroy(q);
}
C语言链队相关操作
最新推荐文章于 2023-05-16 23:33:37 发布