真是无语,自己写好的队列的代码居然搁置了这么长的时间,拿出来晒一晒把:
#include <stdio.h>
#include <stdlib.h>
typedef int QElemType;
typedef int Status;
typedef struct QNode
{
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
//基本操作
Status InitQueue(LinkQueue *Q);
Status DestroyQueue(LinkQueue *Q);
Status ClearQueue(LinkQueue *Q);
Status QueueEmpty(LinkQueue *Q);
Status QueueLength(LinkQueue *Q);
Status GetHead(LinkQueue *Q);
Status EnQueue(LinkQueue *Q,QElemType data);
Status DeQueue(LinkQueue *Q);
Status QueueTraverse(LinkQueue *Q);
//具体实现
Status InitQueue(LinkQueue *Q)
{
Q->front = Q->rear = (QueuePtr)malloc(sizeof(QNode));
if(! Q->front)exit(1);
Q->front->next = NULL;
return 1;
}
Status DestroyQueue(LinkQueue *Q)
{
while(Q->front)
{
Q->rear = Q->front->next;
free(Q->front);
Q->front = Q->rear;
}
return 1;
}
Status ClearQueue(LinkQueue *Q)
{
Q->front = Q->rear = NULL;
return 1;
}
Status QueueEmpty(LinkQueue *Q)
{
return ((Q->front == Q->rear)? 1:0);
}
Status QueueLength(LinkQueue *Q)
{
int flag=0;
QueuePtr temp = Q->front;
while(temp->next)
{
Q->rear = temp->next;
flag++;
temp = Q->rear;
}
return flag;
}
Status GetHead(LinkQueue *Q)
{
if(Q->front == Q->rear)
{
printf("Queue Handle Error.\n");
exit(1);
}
return Q->front->next->data;
}
Status EnQueue(LinkQueue *Q,QElemType data)
{
QueuePtr tmp;
tmp = (QueuePtr)malloc(sizeof(QNode));
tmp->data = data;
tmp->next = NULL;
Q->rear->next = tmp;
Q->rear = tmp;
return 1;
}
Status DeQueue(LinkQueue *Q)
{
QueuePtr temp;
if (Q->front == Q->rear)
{
printf("error.\n");
return 0;
}
temp = Q->front->next;
Q->front->next = temp->next;
if(Q->rear == temp)Q->rear = Q->front; //如果删除的是队列最后一个元素,要将队尾指针重新赋值
free(temp);
return 1;
}
Status QueueTraverse(LinkQueue *Q)
{
QueuePtr temp = Q->front;
if(Q->front == Q->rear)
{
printf("error!\n");
return 0;
}
while(temp->next)
{
Q->rear = temp->next;
printf("%d ",Q->rear->data);
temp = Q->rear;
}
printf("\n");
return 1;
}
int main()
{
QElemType number;
LinkQueue queue;
InitQueue(&queue);
while(scanf("%d",&number) != EOF)
{
EnQueue(&queue,number);
}
printf("当前该队列是 : %-6s\n",QueueEmpty(&queue) ? "空队列":"非空队列");
printf("当前队列长度为: %-6d\n",QueueLength(&queue));
printf("当前队头为: %-6d\n",GetHead(&queue));
printf("当前遍历队列的结果是:\n");
QueueTraverse(&queue);
DestroyQueue(&queue);
return 0;
}