队列的链式存储的实现及操作
用链表表示的队列简称为链队列, 空的链队列的队头和队尾指针均指向头结点
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}LinkQNode;
typedef struct
{
LinkQNode *front;
LinkQNode *rear;
}LinkQueue;
void InitLinkQueue(LinkQueue *Q);
int IsLQEmpty(LinkQueue *Q);
int EnLinkQueue(LinkQueue *Q, int x);
int DeLinkQueue(LinkQueue *Q, int *x);
int GetLQHead(LinkQueue *Q, int *x);
void print_hyphen(int n);
int main(void)
{
LinkQueue LQ;
InitLinkQueue(&LQ);
if(LQ.front)
printf("队列初始化成功!\n");
else{
printf("队列初始化失败!\n");
exit(1);
}
int end = 0;
int ope;
int n;
while(!end){
print_hyphen(15); printf("\n");
printf("请输入指令来执行操作\n");
print_hyphen(15); printf("\n");
printf("1、入队\n2、出队\n3、取队头元素\n4、判断队列是否为空\n5、退出\n");
print_hyphen(15); printf("\n");
printf("输入要使用的功能的序号: ");
scanf("%d", &ope);
getchar();
switch(ope){
case 1:
printf("请输入要入队的数据: ");
scanf("%d", &n);
EnLinkQueue(&LQ, n);
break;
case 2:
if(!DeLinkQueue(&LQ, &n))
printf("队列为空!\n");
else
printf("出队的元素为: %d\n", n);
break;
case 3:
if(!GetLQHead(&LQ, &n))
printf("队列为空!\n");
else
printf("出队的元素为: %d\n", n);
break;
case 4:
if(IsLQEmpty(&LQ))
printf("队列为空!\n");
else
printf("队列不为空! \n");
break;
case 5:
printf("再见!\n");
end = 1;
break;
default:
printf("无此序号,请重新输入!\n");
}
}
return 0;
}
void InitLinkQueue(LinkQueue *Q)
{
Q->front = (LinkQNode*)malloc(sizeof(LinkQNode));
Q->rear = Q->front;
Q->front->next = NULL;
}
int IsLQEmpty(LinkQueue *Q)
{
if(Q->front == Q->rear)
return 1;
else
return 0;
}
int EnLinkQueue(LinkQueue *Q, int x)
{
LinkQNode *NewNode;
NewNode = (LinkQNode*)malloc(sizeof(LinkQNode));
if(NewNode != NULL){
NewNode->data = x;
NewNode->next = NULL;
Q->rear->next = NewNode;
Q->rear = NewNode;
return 1;
}
else
return 0;
}
int DeLinkQueue(LinkQueue *Q, int *x)
{
LinkQNode *p;
if(Q->front == Q->rear)
return 0;
p = Q->front->next;
Q->front->next = p->next;
if(Q->rear == p)
Q->rear = Q->front;
*x = p->data;
free(p);
return 1;
}
int GetLQHead(LinkQueue *Q, int *x)
{
LinkQNode *p;
if(Q->front == Q->rear)
return 0;
*x = Q->front->next->data;
return 1;
}
void print_hyphen(int n)
{
while(n--)
printf("-");
}