#include<iostream>
#include "stdio.h"
using namespace std;
const int MAXSIZE = 20;
const int OK = 1;
const int ERROR =0;
typedef int Status;
typedef int ElemType;
typedef struct QNode
{
ElemType data;
QNode* next;
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front,rear;
}LinkQueue;
/* 构造一个空队列Q */
Status InitQueue(LinkQueue *Q)
{
Q->front=Q->rear=(QueuePtr)malloc(sizeof(QNode));
if(!Q->front)
exit(0);
Q->front->next=NULL;
return OK;
}
Status EnQueue(LinkQueue *Q, ElemType e)
{
QueuePtr s=(QueuePtr)malloc(sizeof(QNode));
/* if(NULL==s)
exit(0);//内存分配失败*/
s->data = e;
s->next = NULL;
Q->rear->next = s;
Q->rear = s;
return OK;
}
Status DelQueue(LinkQueue *Q, ElemType *e)//Q->front相当于链表头
{
QNode* s;
if(Q->front == Q->rear)//链队列空
return ERROR;
s = Q->front->next;
*e = s->data;
Q->front->next= s->next;
if(Q->rear == s)//队列只有一个元素,delete后把rear指向front。
Q->rear = Q->front;
free(s);
return OK;
}
void PrintLinkList(LinkQueue lkQ)
{
cout<<"From front to rear: ";
QNode *p;
p=lkQ.front->next;
while(NULL!=p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
LinkQueue *lkQueueA = (LinkQueue*)malloc(sizeof(LinkQueue));
InitQueue(lkQueueA);//在lkQueueA被当参数使用之前一定要先分配内存,让它有所指向,所以上面先malloc,如果是LinkQueue lkQueueA就可以直接在声明后InitQueue(&lkQueueA);
int i=0;
for(i=0;i<10;i++)
{
EnQueue(lkQueueA,i*i);
cout<<i*i<<"入队列"<<endl;
}
PrintLinkList(*lkQueueA);
ElemType e;
for(i=0;i<5;i++)
{
DelQueue(lkQueueA,&e);
cout<<e<<"出栈"<<endl;
}
PrintLinkList(*lkQueueA);
free(lkQueueA);
getchar();
return 0;
}
队列的链式存储结构
最新推荐文章于 2022-07-20 19:44:39 发布