队列(双链表实现)

来源:互联网 发布:知行理工下载 编辑:程序博客网 时间:2024/06/05 03:53

队列(queue)需要满足FIFO(First In First Out)的要求。

在是使用双链表实现队列时,需要注意下面三种情况:1)队列为空;2)队列只有一个元素;3)队列有多个元素


进栈(Enqueue)


出栈(Dequeue)


#pragma once#ifndef _MY_QUEUE_H#define _MY_QUEUE_Htypedef struct node {struct node *pNext;struct node *pPrev;int key;} Node;typedef struct queue {struct node *pHead;struct node *pTail;} Queue;Queue *InitQueue(Queue *pQueue);Queue *ReleaseQueue(Queue *pQueue);void Enqueue(Queue *pQueue, Node *pCur);Node *Dequeue(Queue *pQueue);Node *GetNodeByKey(Queue *pQueue, int key);int GetQueueSize(Queue *pQueue);void PrintQueueH(Queue *pQueue);void PrintQueueT(Queue *pQueue);#endif // !_MY_QUEUE_H
#include <stdio.h>#include <stdlib.h>#include <string.h>#include "myqueue.h"Queue *InitQueue(Queue *pQueue){pQueue = (Queue *)malloc(sizeof(Queue));if (pQueue == NULL) {printf("malloc error\n");return NULL;} pQueue->pHead = NULL;pQueue->pTail = NULL;return pQueue;}Queue *ReleaseQueue(Queue *pQueue){free(pQueue);return NULL;}void Enqueue(Queue *pQueue, Node *pCur){if (pCur == NULL) {return;}if (pQueue->pTail == NULL) { // emptypQueue->pTail = pCur;pQueue->pHead = pCur;} else {pCur->pPrev = pQueue->pTail;pQueue->pTail->pNext = pCur;pQueue->pTail = pCur;}}Node *Dequeue(Queue *pQueue){Node *pTmp = pQueue->pHead;if (pQueue->pHead == NULL) { // emptyreturn NULL;}if (pQueue->pHead == pQueue->pTail) { // onepQueue->pHead = NULL;pQueue->pTail = NULL;} else {pQueue->pHead = pQueue->pHead->pNext;pQueue->pHead->pPrev = NULL;pTmp->pNext = NULL;}return pTmp;}Node *GetNodeByKey(Queue *pQueue, int key){Node *pIter = pQueue->pHead;while (pIter != NULL && pIter->key != key) {pIter = pIter->pNext;}return pIter;}int GetQueueSize(Queue *pQueue){Node *pIter = pQueue->pHead;int iCount = 0;while (pIter != NULL) {iCount++;pIter = pIter->pNext;}return iCount;}void PrintQueueH(Queue *pQueue){Node *pIter = pQueue->pHead;while (pIter != NULL) {printf("%d\t", pIter->key);pIter = pIter->pNext;}printf("\n");}void PrintQueueT(Queue *pQueue){Node *pIter = pQueue->pTail;while (pIter != NULL) {printf("%d\t", pIter->key);pIter = pIter->pPrev;}printf("\n");}
#include <stdio.h>#include <stdlib.h>#include <string.h>#include "myqueue.h"int main(){Queue *pQueue = NULL;Node *pCur = NULL;int arr[] = { 23, 4, 12, 90, 445, 43, 8, 0, 87 };int size = sizeof(arr) / sizeof(arr[0]);int i = 0;pQueue = InitQueue(pQueue);for (i = 0; i < size; i++) {pCur = (Node *)malloc(sizeof(Node));if (pCur == NULL) {printf("malloc error\n");return -1;}pCur->pNext = NULL;pCur->pPrev = NULL;pCur->key = arr[i];Enqueue(pQueue, pCur);PrintQueueH(pQueue);//PrintQueueT(pQueue);}for (i = 0; i < size; i++) {pCur = Dequeue(pQueue);printf("current node: %d\n", pCur->key);free(pCur);pCur = NULL;PrintQueueH(pQueue);//PrintQueueT(pQueue);}pQueue = ReleaseQueue(pQueue);getchar();return 0;}





0 0
原创粉丝点击