队列c语言实现
程序员文章站
2022-05-26 12:02:07
...
利用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) /* 自定义函数,元素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; /* front is a null head node */
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)); /*storage allocation*/
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;
}
上一篇: 将编号为0和1的两个栈存放于一个数组空间V[m]中。
下一篇: 队列,C语言实现