队列
循环单链表存储(有头结点,只设尾指针,不设头指针)
考研参考书上的代码风格不太能接受,为了巩固加深链表操作的理解,特地完成了循环单链表的各项操作,
加油,一研为定!!
大家有需要可以借鉴,欢迎各位指正错误!!
代码:
#include<cstdio>
#include<malloc.h>
#define M printf("\n\n
typedef struct queuenode{
int data;
struct queuenode *next;
}Queuenode;
typedef struct{
queuenode* rear;
}LinkQueue;
int Empty(LinkQueue *Q){
if(Q->rear->next==Q->rear){
return 1;
}
return 0;
}
LinkQueue* InitQ(){
Queuenode* head = (Queuenode*)malloc(sizeof(Queuenode));
LinkQueue* Q;
Q->rear=head;
Q->rear->next=Q->rear;
M;
printf("循环单链队列创建成功\n\n");
return Q;
}
void EnQueue(LinkQueue* Q,int x){
Queuenode* newnode = (Queuenode*)malloc(sizeof(Queuenode));
newnode->data = x;
newnode->next=Q->rear->next;
Q->rear->next=newnode;
Q->rear=newnode;
M;
printf(" %d 入队成功\n",Q->rear->data);
}
void Dequeue(LinkQueue* Q){
if(Empty(Q)){
M;
printf("出队失败,队列为空\n");
return;
}else{
Queuenode* q = Q->rear->next->next;
if(q==Q->rear){
Q->rear = Q->rear->next;
Q->rear->next=q->next;
}else{
Q->rear->next->next=q->next;
}
M;
printf("%d 出队成功\n\n",q->data);
free(q);
}
}
void print(LinkQueue *Q){
if(Empty(Q)){
M;
printf("队列为空\n");
}
queuenode *q=Q->rear->next->next;
printf("\n");
M;
printf("队列:[");
while(q!=Q->rear->next){
printf(" %d ",q->data);
q=q->next;
}
printf("]\n\n");
}
void deleteQ(LinkQueue *Q){
Queuenode *p = Q->rear->next->next;
Queuenode *q;
Q->rear = Q->rear->next;
while(p!=Q->rear){
q=p;
p=p->next;
free(q);
}
Q->rear->next=Q->rear;
M;
printf(" 队列已清空\n");
}
int getSize(LinkQueue *Q){
int count = 0;
Queuenode *p = Q->rear->next->next;
while(p!=Q->rear->next){
count++;
p=p->next;
}
return count;
}
int main(){
LinkQueue *Q;
bool Qexist=false;
int check=1;
while(check!=0){
printf("\n========================================单链循环队列============================================\n");
printf("\n\n\n 1.创建循环队列 2.入队 3.出队 4.查看队列元素 5.查看队列大小 6.清空队列 7.退出\n\n\n");
M;
printf("请输入人操作:");
scanf("%d",&check);
printf("\n");
if(!Qexist&&check!=1&&check!=6){
M;
printf("请先创建队列!!!\n\n");
continue;
}
switch(check){
case 1:{
if(Qexist){
M;
printf("队列已存在");
}else{
Qexist=true;
Q = InitQ();
}
break;
}
case 2:{
M;
printf("请输入入队元素:");
int x;
scanf("%d",&x);
EnQueue(Q,x);
break;
}
case 3:{
Dequeue(Q);
break;
}
case 4:{
print(Q);
break;
}
case 5:{
M;
printf("队列共有 %d 个元素\n",getSize(Q));
break;
}
case 6:{
deleteQ(Q);
break;
}
case 7:{
exit(0);
break;
}
default:{
M;
printf("输入有误");
}
}
printf("<<按任意键继续>>");
getchar();
getchar();
system("cls");
}
}
|