#include <iostream>
using namespace std;
typedef struct node{
int data;
struct node *next;
}Node,*CycleList;
typedef struct Q{
CycleList head;
CycleList front;
CycleList rear;
}Queue;
void init_queue(Queue &Q) { ///初始化队列
Q.front = new Node;
Q.head=Q.rear = Q.front;
Q.front->data=0;
Q.front->next=NULL;
}
void insert_front(Queue &Q,int e) { ///插入到队首
CycleList p = new Node;
p->data=e;
Q.head->next=p;
p->next=Q.front;
Q.front=p;
///整个过程相当于在头结点和第一个结点间插入了一个结点。然后将头指针移到新插入的结点上。
}
void insert_rear(Queue &Q,int e) { ///插入到队尾
CycleList p = new Node;
p->data=e;
p->next=Q.head;
Q.rear->next=p;
Q.rear=p; ///整个过程相当于在尾结点和头结点间插入了一个结点。然后将尾指针移到新插入的结点上。
}
int del_front(Queue &Q) { ///删除队首 (注意跳过头节点) 元素并返回要删除的元素
if(Q.front==Q.head) Q.front=Q.head->next;
int e=Q.front->data;
Q.front=Q.front->next;
return e;
}
int del_rear(Queue &Q) { /// 删除队尾元素并返回要删除的元素
if(Q.rear == Q.head) while(Q.rear->next!=Q.head) Q.rear=Q.rear->next;
int e=Q.rear->data;
CycleList p=Q.front;
while(p->next!=Q.rear) p=p->next; ///为了找到队尾结点的前一个结点。
p->next=Q.front;
Q.rear=p;
return e;
}
int main()
{
Queue Q;
init_queue(Q);
insert_front(Q,1);
insert_front(Q,2);
insert_front(Q,3);
insert_rear(Q,3);
///此时循环队列里的元素是 3 2 1 3
cout<<del_front(Q)<<endl;
cout<<del_front(Q)<<endl;
//cout<<del_front(Q)<<endl;
cout<<del_rear(Q)<<endl;
///应该输出的是 3 2 3
return 0;
}
循环链表实现循环队列
最新推荐文章于 2024-08-21 23:51:20 发布