链队列其实就是对单链表进行先进先出操作
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data;
struct node* next;
}node, * nodeptr;
typedef struct queue
{
nodeptr front, rear;
}queue,*queueptr;
//链队列其实就是对单链表进行先进先出操作
queueptr creat()
{
nodeptr phead = (nodeptr)malloc(sizeof(node));
queueptr p = (queueptr)malloc(sizeof(queue));
phead->next = NULL;
p->front = phead;
p->rear = phead;
return p;
//返回队列的地址,而不是首结点的地址
//因为返回队列地址可以得到首结点地址,而返回首结点地址不能得到队列的地址
}
void insert(queueptr p,int ele)
{
nodeptr pnew = (nodeptr)malloc(sizeof(node));
pnew->data = ele;
pnew->next = NULL;
p->rear->next = pnew;//让rear此时所指向的结点的next指向新的结点
p->rear = pnew;//让rear指向新构建的结点
}
void print(queueptr p)
{
nodeptr p1 = p->front; int flag = 0;
while (p1->next != NULL)
{
p1 = p1->next;
printf("%d", p1->data);
flag = 1;
}
if (flag == 1)
{
printf("\n");
}
else
{
printf("the queue is empty\n");
}
}
void deleteelement(queueptr p)
{
nodeptr p2 = p->front->next;
if (p2 == NULL)
{
printf("fail to delete cause the queue is already empty\n");
return;
}
p->front->next= p->front->next->next;
free(p2);
}
//front指向的一直是phead
//free掉phead->next指向的node
int main()
{
queueptr p = creat(); int i;
for (i = 0; i < 5; i++)
{
insert(p, i);
print(p);
}
for (i = 0; i < 5; i++)
{
deleteelement(p);
print(p);
}
deleteelement(p);
print(p);
}
运行结果:
0
01
012
0123
01234
1234
234
34
4
the queue is empty
fail to delete cause the queue is already empty
the queue is empty