链队列
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node
{
int Data;
struct Node *next;
}LinkQueueNode,*PLinkQueueNode;
typedef struct
{
PLinkQueueNode front;
PLinkQueueNode rear;
}LinkQueue,*PLinkQueue;
int IsEmpty(PLinkQueue Q)
{
return(Q->front==NULL);
}
void CreateQueue(PLinkQueue* Q)
{
(*Q)=(PLinkQueue)malloc(sizeof(LinkQueue)); //这个是为主函数创一个Q空间,不然主函数就乱找空间了,虽然这个空间为空,但是是起点。
PLinkQueueNode front=(PLinkQueueNode)malloc(sizeof(LinkQueue));
front=NULL;
PLinkQueueNode rear=(PLinkQueueNode)malloc(sizeof(LinkQueue));
rear=NULL;
(*Q)->rear=rear;
(*Q)->front=front;
return;
}
void Push(PLinkQueue Q,int x)
{
PLinkQueueNode p;
p=(PLinkQueueNode)malloc(sizeof(LinkQueueNode));
p->Data=x;
p->next=NULL;
if(IsEmpty(Q))
{
Q->front=p;
Q->rear=p;
}
else
{
Q->rear->next=p; //尾结点,尾接法
Q->rear=p;
}
return;
}
void Pop(PLinkQueue Q)
{
if(!IsEmpty(Q))
{
PLinkQueueNode p;
p=Q->front;
if(Q->front==Q->rear)
Q->front=Q->rear=NULL;
/*Q->front->next=Q->front->next->next; 这样无法free*/
else
Q->front=Q->front->next;
free(p);
}
return;
}
void Print(PLinkQueue Q)
{
PLinkQueueNode p;
p=Q->front;
while(p!=Q->rear)
{
printf("%d ",p->Data);
p=p->next;
}
printf("%d\n",p->Data);
return;
}
int main()
{
int n;
scanf("%d",&n);
PLinkQueue Q;
CreateQueue(&Q);
int i;
int x;
for(i=1;i<=n;i++)
{
scanf("%d",&x);
Push(Q,x);
}
for(i=1;i<=n;i++)
{
Print(Q);
Pop(Q);
}
return 0;
}