#include <stdio.h>
#include <malloc.h>
/*
*链队列的节点.
*/
typedef struct LinkNode {
int data;
struct LinkNode* next;
}*LinkNodePtr;
/*
*链队列.
*/
typedef struct LinkQueue {
LinkNodePtr front;
LinkNodePtr rear;
}*LinkQueuePtr;
/*
*Construct an empty queue.
*/
LinkQueuePtr initQueue() {
LinkQueuePtr resultPtr = (LinkQueuePtr)malloc(sizeof(struct LinkQueue));
//The header, the data is not useful.
LinkNodePtr headerPtr = (LinkNodePtr)malloc(sizeof(struct LinkNode));
headerPtr->next = NULL;
resultPtr->front = headerPtr;
resultPtr->rear = headerPtr;
return resultPtr;
}
/*
*Output the queue.
*/
void outputLinkQueue(LinkQueuePtr paraQueuePtr) {
LinkNodePtr tempPtr = paraQueuePtr->front->next;
while (tempPtr != NULL) {
printf("%d ", tempPtr->data);
tempPtr = tempPtr->next;
}
printf("\r\n");
}
/**
*Enqueue.
*/
void enqueue(LinkQueuePtr paraQueuePtr, int paraElement) {
//Step 1: Create a new node
LinkNodePtr tempNodePtr = (LinkNodePtr)malloc(sizeof(struct LinkNode));
tempNodePtr->data = paraElement;
tempNodePtr->next = NULL;
//Step 2: Link to the existing rear
paraQueuePtr->rear->next = tempNodePtr;
//Step 3: It is the new rear
paraQueuePtr->rear = tempNodePtr;
}
/*
*Dequeue.
*@return The value of the header
*/
int dequeue(LinkQueuePtr paraQueuePtr) {
int resultValue;
LinkNodePtr tempNodePtr;
//Step 1: Is the queue empty
if (paraQueuePtr->front == paraQueuePtr->rear) {
printf("The queue is empty.\r\n");
return -1;
}
//Step 2: Change the queue
tempNodePtr = paraQueuePtr->front->next;
resultValue = tempNodePtr->data;
paraQueuePtr->front->next = paraQueuePtr->front->next->next;
if (paraQueuePtr->rear == tempNodePtr) {
paraQueuePtr->rear = paraQueuePtr->front;
}
//Step 3: Free space
// free(tempNodePtr);
tempNodePtr = NULL;
//Step 4: Return.
return resultValue;
}
/**
*Unit test.
*/
void testLinkQueue() {
LinkQueuePtr tempQueuePtr;
tempQueuePtr = initQueue();
enqueue(tempQueuePtr, 10);
enqueue(tempQueuePtr, 30);
enqueue(tempQueuePtr, 50);
outputLinkQueue(tempQueuePtr);
printf("dequeue gets %d\r\n", dequeue(tempQueuePtr));
printf("dequeue gets %d\r\n", dequeue(tempQueuePtr));
printf("dequeue gets %d\r\n", dequeue(tempQueuePtr));
printf("dequeue gets %d\r\n", dequeue(tempQueuePtr));
enqueue(tempQueuePtr, 8);
outputLinkQueue(tempQueuePtr);
}
/**
*The entrance.
*/
int main() {
testLinkQueue();
return 1;
}
链队列是一个链式储存的线性数据结构,使用链表作为主要工具。链队列包含两个指针,队头指针和队尾指针,队头指针指向第一个元素,队尾指向下一个节点,入队时,元素会添加到链表末尾,更新队尾指针。出队时,队列开头会移除一个元素,更新队头指针。链队列的时间复杂度较低,但空间复杂度高,因为需要额外的空间储存两个指针和系列的头结点。