利用c语言实现链队列及相关操作
#include <stdio.h>
#include <stdlib.h>
#define ElemType int
typedef struct node
{
ElemType data;
struct node * next;
}quenode,*quenlist;
struct quefr
{
quenode *front, *rear;
};
void creat(struct quefr *q)
{
quenode *h;
h = (quenlist)malloc(sizeof(quenode));
h->next = NULL;
q->front = h;
q->rear = h;
};
void enqueue(struct quefr *q, ElemType x)
{
quenode *s;
s = (quenode*)malloc(sizeof(quenode));
s->data = x;
s->next = NULL;
q->rear->next = s;
q->rear = s;
}
ElemType dequenue(struct quefr *q)
{
quenode *p;
ElemType x;
p = (quenode*)malloc(sizeof(quenode));
if(q->front == q->rear)
{
printf("Quenue is NULL.\n");
exit(1);
}
else
{
p=q->front->next;
q->front->next = p->next;
if(p->next == NULL)
q->front = q->rear;
x = p->data;
free(p);
}
return x;
}
void display(struct quefr* dp)
{
quenode* p;
if(dp->front == dp->rear)
{
printf("queue is NULL!\n");
exit(1);
}
p = dp->front->next;
while(p != NULL)
{
printf("data = %d\n", p->data);
p = p->next;
}printf("end!");
}
int main()
{
struct quefr *que;
int n,i,x,sel;
void display();
void creat();
void enqueue();
ElemType dequenue();
do
{
printf("\n\n");
printf("1 create queue \n");
printf("2 enqueue \n");
printf("3 dequeue \n");
printf("4 display \n");
printf("5 exit \n");
printf("-----------------------\n");
printf("please chose (1 2 3 4 5):\n");
scanf("%d",&sel);
switch(sel)
{
case 1:
{
que = (struct quefr*)malloc(sizeof(struct quefr));
creat(que);
printf("please input the number of element which do you want to creat:\n");
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf("%d", &x);
enqueue(que,x);
}
break;
}
case 2:
{
printf("please input the element:\n");
scanf("%d", &x);
enqueue(que,x);
break;
}
case 3:
{
printf("x = %d\n", dequenue(que));
break;
}
case 4:
{
display(que);
break;
}
case 5:
exit(0);
}
}while(sel <= 4);
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2aa8337d3cf560482fc6480f369e6544.png)