一. 链队列的简单操作
以下为一些基础的操作函数。
1.1 链队列的定义
#include<bits/stdc++.h>
using namespace std;
//链队列
typedef int ElemType;
//定义链队列
typedef struct QNode{
ElemType x; //x坐标
ElemType y; //y坐标
struct QNode* next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
1.2 初始化链队列
//初始化链队列
void InitQueue(LinkQueue &Q){
Q.front=(QueuePtr)malloc(sizeof(QNode));
Q.rear=Q.front;
Q.rear->next=NULL;
}
1.3 入队操作和出队操作
//链队列的入队操作
void EnQueue(LinkQueue &Q,ElemType x,ElemType y){
QueuePtr q=(QueuePtr)malloc(sizeof(QNode));
q->x=x;
q->y=y;
q->next=NULL;
Q.rear->next=q;
Q.rear=q;
return;
}
//链队列的出队操作
bool DeQueue(LinkQueue &Q,ElemType *x,ElemType *y){
//空表返回false
if(Q.front==Q.rear){
return false;
}
//头结点
QueuePtr q=Q.front->next;
*x=q->x;
*y=q->y;
Q.front->next=q->next;
//若链表里仅有一个结点,出队后将尾指针归NULL
if(Q.rear==q){
Q.rear=Q.front;
}
free(q);
return true;
}
1.4 打印链队列
//打印队列
void ShowQueue(LinkQueue &Q){
QueuePtr q=Q.front->next;
printf("队列元素:\n");
while(q!=NULL){
cout<<q->x<<" "<<q->y<<endl;
q=q->next;
}
}
1.5 链队列的长度
//链队列长度
int QueueLength(LinkQueue &Q){
int count=0;
QueuePtr q=Q.front->next;
while(q!=NULL){
count++;
q=q->next;
}
return count;
}
1.6 主函数
简单应用。
int main(){
LinkQueue Q;
//初始化链队列
InitQueue(Q);
for(int i=0;i<=6;i++){
//入队操作
EnQueue(Q,i,i);
}
//打印队列
ShowQueue(Q);
//链队列长度
int len=QueueLength(Q);
cout<<"链队列长度:"<<len<<endl;
//出队操作
int x,y;
DeQueue(Q,&x,&y);
printf("出队一次:");
cout<<x<<" "<<y<<endl;
//打印队列
ShowQueue(Q);
len=QueueLength(Q);
cout<<"链队列长度:"<<len<<endl;
return 0;
}