双向链表的队列实现
#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)
{
printf("%d ", pscan->item.wait_time);
pscan = pscan->next;
}
putchar('\n');
pscan = pq->rear;
while (pscan != pq->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;
}