cpp
#include <iostream>
using namespace std;
// 链队列
typedef int ElemType;
typedef struct LinkNode
{
ElemType data;
struct LinkNode *next;
} LinkNode;
typedef struct
{
LinkNode *front, *rear;
} LinkQueue;
// 初始化
void InitQueue(LinkQueue &Q)
{
Q.front = Q.rear = (LinkNode *)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
// 入队
bool EnQueue(LinkQueue &Q, ElemType x)
{
LinkNode *p = (LinkNode *)malloc(sizeof(LinkNode));
p->data = x;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return true;
}
// 出队
bool DeQueue(LinkQueue &Q, ElemType &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 Traverse(LinkQueue Q)
{
LinkNode *p = Q.front->next;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
// 长度
int QueueLength(LinkQueue Q)
{
int length = 0;
LinkNode *p = Q.front->next;
while (p != NULL)
{
length++;
p = p->next;
}
return length;
}
int main()
{
LinkQueue Q;
ElemType x;
InitQueue(Q);
EnQueue(Q, 1);
EnQueue(Q, 2);
EnQueue(Q, 3);
EnQueue(Q, 4);
DeQueue(Q, x);
Traverse(Q);
cout << QueueLength(Q) << endl;
return 0;
}