#include <stdio.h>
#include <malloc.h>
typedef int T;
typedef struct QNode
{
T data;//数据
QNode* next;//指向下一结点
}*Node;
typedef struct
{
Node front, rear;//头、尾指针
int count;//计数器
}*LinkQuene;
bool InitQuene(LinkQuene q)//初始化
{
q->front = q->rear = (Node)malloc(sizeof(Node));
q->front->next = NULL;
q->count = 0;
return true;
}
bool DetoryQuene(LinkQuene Q)//销毁
{
while (Q->front)
{
Q->rear = Q->front->next;
free(Q->front);
Q->front = Q->rear;
}
Q->count = 0;
return true;
}
bool ClearQuene(LinkQuene Q)//清队
{
Node p, q;
Q->rear = Q->front;
p = Q->front;
Q->front->next = NULL;
while (p)
{
q = p->next;
free(p);
p = q;
}
Q->count = true;
return true;
}
bool Is_Empty(LinkQuene Q)//判空
{
return Q->front == Q->rear;
}
int GetLength(LinkQuene q)//队列长度
{
return q->count;
}
T GetHead(LinkQuene q)//头元素
{
return q->front->next->data;
}
bool Push(LinkQuene q, T val)//入队
{
if (!q)
return false;
Node node = (Node)malloc(sizeof (Node));
node->data = val;
node->next = NULL;
q->rear->next = node;
q->rear = node;
q->count++;
return true;
}
T Pop(LinkQuene Q)//出队
{
if (!Q)
return false;
Node p;
T tmp;
p = Q->front->next;
tmp = p->data;
Q->front->next = p->next;
if (p == Q->rear)
Q->rear = Q->front;
//free(p);
Q->count--;
return true;
}
void Show(LinkQuene Q)//遍历
{
Node p;
p = Q->front->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
LinkQuene Q = (LinkQuene)malloc(sizeof(LinkQuene));
InitQuene(Q);
for (int i = 1; i <= 5; i++)
{
Push(Q, i);
}
Show(Q);
printf("Head: %d\n", GetHead(Q));
printf("Len: %d\n", GetLength(Q));
printf("Pop: %d\n", Pop(Q));
return 0;
}
链队列
最新推荐文章于 2020-09-25 11:55:09 发布