#include<stdio.h>
#include<stdlib.h>
//using namespace std;
#define OK 1
typedef int QElemType;
typedef int Status;
struct QNode{
QElemType data;
struct QNode *next;
};//定义节点
typedef struct{
struct QNode * rear;//尾指针
struct QNode * front;//头指针
int Length;
}LinkQueue;//定义队列
Status InitQueue(LinkQueue &Q);//初始化队列
Status EnQueue(LinkQueue &Q,QElemType e);//入队在队尾插入元素e
Status ShowQueue(LinkQueue Q);//打印当前队列元素
Status GetTop(LinkQueue Q,QElemType &e);//获取当前队头元素,并用e返回
Status DeQueue(LinkQueue &Q);//出队
Status IsEmptyQueue(LinkQueue Q);//判断是否为空,队空返回1。
Status ClearQueue(LinkQueue &Q);//清空队列
Status DestroyQueue(LinkQueue &Q);//销毁队列
Status InitQueue(LinkQueue &Q){//传地址,修改Q
Q.rear=Q.front=(QNode *)malloc(sizeof(QNode));//指向头结点
if(!Q.rear)
printf("Error Overflow!\n");
Q.front->next=NULL;
Q.Length=0;
return 0;
}
Status EnQueue(LinkQueue &Q,QElemType e){
//在队尾插入新的节点,需要开辟空间
QNode *p=(QNode *)malloc(sizeof(QNode));
if(!p) printf("分配内存失败\n");
p->data=e;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
if(Q.front->next==NULL)
Q.front->next=p;
Q.Length++;
return 0;
}
Status ShowQueue(LinkQueue Q){
QNode *p;
p=Q.front->next;//p指向第一个元素
if(Q.front==Q.rear)
{
printf("\n当前队列为空!没有元素可以显示");
return 0;
}
printf("当前队列共计 %d 个元素\n",Q.Length);
printf("-----------------当前队列元素为:-------------------\n");
while(p!=Q.rear)
{
printf("%d ",p->data);
p=p->next;//不能用p++
}
printf("%d\n",p->data);
return 0;
}
Status GetTop(LinkQueue Q,QElemType &e){
e=Q.front->next->data;
return OK;
}
Status DeQueue(LinkQueue &Q){
if(Q.front==Q.rear)
printf("\n队列为空,没有元素可以删除!\n");
else
{
Q.front->next=Q.front->next->next;
Q.Length--;
}
return OK;
}
Status IsEmptyQueue(LinkQueue Q){
if(Q.front==Q.rear)
return 1;
else
return 0;
}
Status DestroyQueue(LinkQueue &Q){
if(Q.front!= NULL)
{
Q.rear=Q.front->next;
free(Q.front);
Q.front=Q.rear; //释放一块内存要做两点:1.释放指向它的指针。2.将该指针指向空
}
return OK;
}
Status ClearQueue(LinkQueue &Q)
{ // 将Q清为空队列
struct QNode *p,*q;
Q.rear=Q.front;
p=Q.front->next;
Q.front->next=NULL;//只留下头结点
while(p)
{
q=p;
p=p->next;
free(q);
}
return OK;
}
int main(int argc,char *argv[]){
LinkQueue Q;//结构体Q
InitQueue(Q);
QElemType e;
e=rand()%100;
int n;//随机插入队列元素的数目。
printf("请输入队列随机元素数目:");
scanf("%d",&n);
while(n--)
{
e=rand()%100;
EnQueue(Q,e);//进队n个元素
}
GetTop(Q,e);
printf("当前队头元素为:%d\n",e);
ShowQueue(Q);
DeQueue(Q);
printf("\n-----------------队头元素出队后:------------------------\n");
GetTop(Q,e);
printf("当前队头元素为: %d\n",e);
ShowQueue(Q);
if(!IsEmptyQueue(Q))
printf("队列非空\n");
e=rand()%50;
printf("入队的元素为%d\n",e);
EnQueue(Q,e);//再次入队
GetTop(Q,e);
printf("当前队头元素为:%d\n",e);
ShowQueue(Q);
//清空
printf("\n-----------清空队列--------\n");
DestroyQueue(Q);
ShowQueue(Q);
return 0;
}
链队
最新推荐文章于 2023-04-24 15:40:14 发布