链式队列的基本操作(入队和出队)
?#include <stdio.h>
?#include <stdlib.h>
?#include <malloc.h>
//链式队列
typedef struct LNode{
int data;
struct LNode *next;
}LNode, *Linklist;
typedef struct LinkQueue{
Linklist front;//队头指针
Linklist rear; //队尾指针
}LinkQueue;
//初始化链式队列
bool InitQueue(LinkQueue &Q){
Q.front = (Linklist)malloc(sizeof(LNode));//队头指针
if(!Q.front)
return false;
Q.front->next = NULL;
Q.rear = Q.front;
}
//入队
void EnQueue(LinkQueue &Q,int x){
Linklist s = (Linklist)malloc(sizeof(LNode));
s->data = x;
s->next = NULL;
Q.rear->next = s;
Q.rear = s;
}
//空队
bool IsEmpty(LinkQueue Q){
if(Q.front == Q.rear)
return true;
else
return false;
}
//出队
bool OutQueue(LinkQueue &Q,int &x){
if (IsEmpty(Q))//调用空队函数
return false;//空队
Linklist s = (Linklist)malloc(sizeof(LNode));
s = Q.front->next;
x = s->data;
Q.front->next = s->next;//
if(s==Q.rear){//若原队列中只有一个节点,删除后置为空队列
Q.rear = Q.front;
}
free(s);
return true;
}
//输出队列
void Print(LinkQueue Q){
Linklist q = (Linklist)malloc(sizeof(LNode));
q = Q.front->next;
while(q){
printf("%d
",q->data);
q = q->next;
}
}
int main(){
LinkQueue Q;
InitQueue(Q);
int n,j;
printf("请输入你要输入队列的数量:
");
scanf("%d",&n);
printf("————————
");
for(int i=0;i<n;i++){
scanf("%d",&j);
EnQueue(Q,j);
}
int x;
if(OutQueue(Q,x)){
printf("出队成功,出队元素是:%d
",x);
}
else
{
printf("出队失败!
");
}
// printf("%d
",x);
Print(Q);
return 0;
}