赞
踩
//双向链队列的实现 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct { int wait_time;//等待时间 }Item; typedef struct node { Item item; struct node* next;//指向下一个指针 struct node* piror;//指向前一个指针 }Node; typedef struct { Node* rear;//队尾指针 Node* front;//队首指针 int node_num;//节点数量 }Queue; bool InitQueue(Queue* pq);//初始化队列 bool QueueIsEmpty(Queue* pq);//判断队列是否为空 bool QueueIsFull(Queue* pq);//判断队列是否已满 bool InQueue(Queue* pq, int n);//入队 bool OutQueue(Queue* pq);//出队 bool FreeQueue(Queue* pq);//释放队列 void ShowQueue(Queue* pq);//展现队列 bool InitQueue(Queue* pq) { pq->rear = (Node*)malloc(sizeof(Node)); pq->front = (Node*)malloc(sizeof(Node)); pq->node_num = 0; pq->rear = pq->front; if (pq->rear == NULL) return false; if (pq->front == NULL) return false; return true; } bool QueueIsEmpty(Queue* pq) { if (pq->rear == pq->front) return true; else return false; } bool QueueIsFull(Queue* pq) { Node* pnew; pnew = (Node*)malloc(sizeof(Node)); if (pnew == NULL) { free(pnew); return true; } else { free(pnew); return false; } } bool InQueue(Queue* pq, int n) { Node* pnew; pnew = (Node*)malloc(sizeof(Node)); if (pnew == NULL) return false; pnew->item.wait_time = n; if (QueueIsFull(pq) == true) { printf("队列已满,无法入队!\n"); return false; } else if (QueueIsEmpty(pq) == true) { pq->front->piror = NULL;//队首前面不会排节点 pq->front->next = pnew;//队首之后是新节点 pnew->piror = pq->front;//把新节点排在队首后面,必须在前两条之后实现 pnew->next = NULL;//新节点后面没有节点 pq->rear = pnew;//新节点作为队尾,必须最后实现 } else { pq->rear->next = pnew; pnew->piror = pq->rear; pnew->next = NULL; pq->rear = pnew; } return true; } bool OutQueue(Queue* pq) { Node* ptemp; if (QueueIsEmpty(pq) == true) { printf("队列为空!出队失败!\n"); return false; } else { ptemp = pq->front; pq->front = pq->front->next; free(ptemp); return true; } } bool FreeQueue(Queue* pq) { Node* psave = pq->front; if (QueueIsEmpty(pq) == true) { printf("队空,不需要释放内存\n"); return false; } while (psave != NULL) { pq->front = pq->front->next; free(psave); } return true; } void ShowQueue(Queue* pq) { Node* pscan; if (QueueIsEmpty(pq) == true) printf("队列为空!\n"); else { pscan = pq->front->next; while (pscan != NULL)//rear->next = NULL,rear有内容 { printf("%d ", pscan->item.wait_time); pscan = pscan->next; } putchar('\n'); pscan = pq->rear; while (pscan != pq->front)//front没内容,且不为空指针 { printf("%d ", pscan->item.wait_time); pscan = pscan->piror; } } } int main() { Queue Q; Item item; if (InitQueue(&Q) == true) printf("程序运行……\n"); else exit(1); while (scanf("%d", &item.wait_time) == 1) { while (getchar() != '\n') continue; InQueue(&Q, item.wait_time); } OutQueue(&Q); ShowQueue(&Q); FreeQueue(&Q); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。