1、代码如下
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct QNode
{
ElemType date;
struct QNode* next;
}QNode,*QueuePtr;
typedef struct LinkQueue
{
QueuePtr front;//头指针
QueuePtr tail;//尾指针
}LinkQueue;
//建立新结点
QNode* New(int x)
{
QNode * newnode = (QNode*)malloc(sizeof(QNode));
if(newnode==NULL)
exit(0);
newnode->date = x;
newnode->next = NULL;
return newnode;
}
//初始化,建立头节点
void InitQueue(LinkQueue* Q)
{
Q->tail=Q->front = (QNode*)malloc(sizeof(QNode));//开始时头尾指针都指向头节点
if (Q->front == NULL)
exit(0);
Q->front->next = NULL;
}
//入队,队尾插入元素
void EnQueue(LinkQueue* Q, ElemType x)
{
QNode* newnode = New(x);
Q->tail->next = newnode;//刚开始时tail,front,都指向头节点
Q ->tail= newnode;//更新尾节点
}
//出队,队头删除元素;现金先出
void DeQueue(LinkQueue* Q,ElemType *x)
{
if (Q->front == Q->tail)
{
printf("链队为空\n");
exit(0);
}
QNode* p = Q->front->next;//定义一个p指针用于指向第一个节点,便于释放空间
*x = p->date;
Q->front->next = p->next;
if (p == Q->tail)//若链队中只剩一个节点如果不进行该操作,当把这个节点空间释放后尾指针便成了野指针
{
Q->tail = Q->front;
}
free(p);
}
//打印
void print(LinkQueue Q)
{
if (Q.front == Q.tail)
{
printf("该链队为空");
exit(0);
}
if (Q.front == NULL)
{
printf("该链队不存在\n");
}
printf("链队中的元素为:");
while (Q.front->next != NULL)//链栈不为空
{
Q.front = Q.front->next;
printf("%d\t", Q.front->date);
//Q.front = Q.front->next;
}
printf("\n");
}
//取链队的队头元素
ElemType GetHead(LinkQueue Q)
{
if (Q.front == Q.tail)
{
printf("该链队为空\n");
exit(0);
}
int x = Q.front->next->date;
return x;
}
//销毁
void Destroy(LinkQueue* Q)
{
if (Q->tail == Q->front)
{
free(Q->front);
Q->tail = Q->front = NULL;
}
while (Q->front != NULL)
{
Q->tail = Q->front->next;
free(Q->front);
Q->front = Q->tail;
}
printf("销毁成功\n");
}
int main()
{
int n,i;
LinkQueue Q;//定义链队
InitQueue(&Q);//初始化链队
printf("请输入进入链队的数目:");
scanf_s("%d", &n);
for (i = 0; i < n; i++)
{
int j;
printf("入队:");
scanf_s("%d", &j);
EnQueue(&Q, j);
}
//打印
print(Q);
//出队
int j = 0;
DeQueue(&Q,&j);
printf("出队元素为:%d\n", j);
printf("出队后:");
print(Q);
Destroy(&Q);
print(Q);
return 0;
}
2、运行结果如下: