# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
typedef struct Node
{
int data;
struct Node * pNext;
}* PNODE, NODE;
typedef struct Queue
{
PNODE pFront;
PNODE pRare;
}* PQUEUE, QUEUE;
//初始化
void init(PQUEUE pQ)
{
pQ->pFront = NULL;
pQ->pRare = NULL;
return;
}
//入队
void inqueue(PQUEUE pQ, int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (!pNew)
{
printf("内存分配失败!\n");
exit(-1);
}
else
{
pNew->data = val;
pNew->pNext = NULL;
if (!pQ->pFront)
{
pQ->pFront = pNew; //有一个及一个以上元素的时候保证pQ->pFront不改变
}
else
{
pQ->pRare->pNext = pNew; //只有一个元素的时候pQ->pRare->pNext还不存在
//有一个及一个以上元素的时候把后一元素的地址赋给前一元素的地址域
}
pQ->pRare = pNew;
printf("入队成功!\n");
}
return;
}
//遍历
void traverse(PQUEUE pQ)
{
PNODE pTemp = pQ->pFront;
if (!pQ->pFront)
{
printf("遍历失败,空队列!\n");
return;
}
else
{
while (pTemp)
{
printf("%d\n", pTemp->data);
pTemp = pTemp->pNext;
}
printf("遍历完毕!\n");
}
return;
}
//出队
void outqueue(PQUEUE pQ)
{
if (!pQ->pFront->pNext)
{
printf("队列为空!\n");
return;
}
else
{
printf("出队成功,出队元素为:%d\n", pQ->pFront->data);
pQ->pFront = pQ->pFront->pNext;
}
return;
}
//清空
void clear(PQUEUE pQ)
{
PNODE pTemp = pQ->pFront;
if (!pQ->pFront)
{
printf("空队列!\n");
}
else
{
while (pQ->pFront)
{
pQ->pFront = pQ->pFront->pNext;
free(pTemp);
pTemp = pQ->pFront;
}
}
pTemp = NULL;
return;
}
int main(void)
{
QUEUE q;
init(&q);
inqueue(&q, 1);
inqueue(&q, 2);
inqueue(&q, 3);
inqueue(&q, 4);
inqueue(&q, 5);
traverse(&q);
outqueue(&q);
traverse(&q);
clear(&q);
traverse(&q);
return 0;
}