用链表表示的队列就简称为链队列。链式队列是也是和链式栈一样采用链表的方式来表现,链式队列针对数据比较灵活的数据比较方便,因为它不像顺序队列一样需要定义最大值,链式队列只需要建立新结点,比较灵活,没有大小限制,只要内存,并且用完了就释放了,对于变动较大的数据很友好。一个链队列需要两个分别指示队头和队尾的指针(分别称为头指针和尾指针)才能惟一确定。判断队列是否为空, 只需要看头指针是否等于尾指针.
#include <stdio.h>
#include <malloc.h>
/**
* 链队列的节点.
*/
typedef struct LinkNode{
int data;
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 valude 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;
}
运行结果:
10 30 50
dequeue gets 10
dequeue gets 30
dequeue gets 50
The queue is empty.
dequeue gets -1
8