链队列
带头结点
//带头结点
//不存在队列满且产生溢出的问题
//头指针指向队头结点 尾指针指向队尾结点
//在带头结点的链队列中,头指针永远指向头结点不变
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef struct LinkNode{
int data;
struct LinkNode *next;
}LinkNode;
typedef struct {
LinkNode *front,*rear;
}LinkQueue;
//初始化
bool InitLinkQueue(LinkQueue &Q){
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
//判空
bool IsEmpty(LinkQueue &Q){
if (Q.rear == Q.front)
return true;
else
return false;
}
//入队
bool EnQueue(LinkQueue &Q, int x){
LinkNode *s = (LinkNode*)malloc(sizeof(LinkNode));
s->data = x; s->next = NULL;
Q.rear->next = s;
Q.rear = s;
return true;
}
//出队
bool DeQueue(LinkQueue &Q, int &x){
if (Q.front == Q.rear)
return false;
LinkNode *p = Q.front->next;//头结点的下一个结点
x = p->data;
Q.front->next = p->next;
if (Q.rear == p)
Q.rear = Q.front; //若只剩下一个结点,修改尾指针
free(p);
return true;
}
void PrintQueue(LinkQueue &Q){
LinkNode *p = Q.front->next;
while (p != NULL){
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main(){
LinkQueue Q;
InitLinkQueue(Q);
int n;
cin >> n;
for (int i = 0; i < n; i ++)
{
int x;
cin >> x;
EnQueue(Q,x);
}
//PrintQueue(Q);
for (int i = 0; i < n; i ++)
{
int x;
DeQueue(Q,x);
cout << x << " ";
}
cout << endl;
return 0;
}
/*
4
1 0 2 4
*/
不带头结点
//链队列
//不带头结点 不存在队列满且产生溢出的问题
//头指针指向队头结点 尾指针指向队尾结点
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef struct LinkNode{
int data;
struct LinkNode *next;
}LinkNode;
typedef struct {
LinkNode *front,*rear;
}LinkQueue;
//初始化
void InitLinkQueue(LinkQueue &Q){
Q.front = Q.rear = NULL;
}
//判空
bool IsEmpty(LinkQueue &Q){
if (Q.rear == NULL)
return true;
else
return false;
}
//入队
bool EnQueue(LinkQueue &Q, int x){
LinkNode *s = (LinkNode*)malloc(sizeof(LinkNode));
s->data = x; s->next = NULL;
if (Q.front == NULL){//判断是不是第一个元素
Q.front = s;
Q.rear = s;
} else{
Q.rear->next = s;
Q.rear = s;
}
return true;
}
//出队
bool DeQueue(LinkQueue &Q, int &x){
if (Q.front == NULL)
return false;
LinkNode *p = Q.front;
x = p->data;
Q.front = p->next;
if (Q.rear == p)
Q.rear = Q.front = NULL; //若只剩下一个结点,修改尾指针
free(p);
return true;
}
void PrintQueue(LinkQueue &Q){
LinkNode *p = Q.front;
while (p != NULL){
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main(){
LinkQueue Q;
InitLinkQueue(Q);
int n;
cin >> n;
for (int i = 0; i < n; i ++)
{
int x;
cin >> x;
EnQueue(Q,x);
}
PrintQueue(Q);
for (int i = 0; i < n; i ++)
{
int x;
DeQueue(Q,x);
cout << x << " ";
}
cout << endl;
return 0;
}
/*
4
1 0 2 4
*/