#include<stdio.h>
#include<iostream.h>
#include<malloc.h>//free
#include<cstdlib>
#include<math.h>
#include<string.h>
#define MAXSIZE 100
#define OK 1
#define ERROR 0//宏
typedef int Status;
typedef struct
{//类似于对象
char name[10];
int num;
}QElemType;
typedef struct QNode
{
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct
{//链队需要分别指示队头和队尾的指针才能被唯一确定
QueuePtr front;
QueuePtr rear;
}LinkQueue;
Status InitQueue(LinkQueue &Q)
{
Q.front=(QNode *)malloc(sizeof(QNode));
Q.rear=Q.front;
Q.front->next=NULL;
return OK;
}
Status EnQueue(LinkQueue &Q,QElemType e)
{//需要为入队元素动态分配结点空间
QNode *q=(QNode *)malloc(sizeof(QNode));
q->data=e;
q->next=NULL;
Q.rear->next=q;
Q.rear=q;
return OK;
}
Status DeQueue(LinkQueue &Q)
{
if(Q.front==Q.rear)return ERROR;
QNode *q=Q.front->next;
Q.front->next=q->next;
if(q=Q.rear)Q.rear=Q.front;
delete q;
return OK;
}
QElemType GetHead(LinkQueue Q)
{//读取队头元素
if(Q.front!=Q.rear)
return Q.front->next->data;
cout<<"空队列,没有头元素"<<endl;
}
Status TraverseQueue(LinkQueue Q)
{
if(Q.front==Q.rear)
{
cout<<"Empty Queue!"<<endl;
return ERROR;
}
QNode *q;
q=Q.front->next;
while(q)
{
cout<<"编号:"<<q->data.num<<" 名字:"<<q->data.name<<endl;
q=q->next;
}
return OK;
}
void main()
{
LinkQueue Q;QElemType e,a;
e.num=00001;
strcpy(e.name,"张三");
cout<<InitQueue(Q)<<endl;
EnQueue(Q,e);
a=GetHead(Q);
cout<<"队头"<<e.num<<e.name<<endl;
TraverseQueue(Q);
DeQueue(Q);
TraverseQueue(Q);
system("pause");
}
链队的表示和实现
最新推荐文章于 2022-04-22 18:39:02 发布