[英]How to display the elements of a queue implemented using linked list in c?
I implemented the queue using linked list.我使用链表实现了队列。 The display function is only printing the last element.
display 函数只打印最后一个元素。 But I want to display all the elements.
但我想显示所有元素。 Can somebody correct it?
有人可以纠正吗? What are the other ways to write the display function?
显示函数还有哪些写法? Is the node declaration wrong?
节点声明错误吗?
My code is as follows:我的代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef int QueueElement;
typedef enum {TRUE,FALSE} Boolean;
typedef struct node{
QueueElement entry;
struct node *next;
} Node;
typedef struct{
int count;
Boolean full;
Node *front;
Node *rear;
} Queue;
void createQueue(Queue *q){
q->count=0;
q->front=q->rear=NULL;
q->full=FALSE;
}
Boolean IsFull(Queue *q){
return (q->full);
}
Boolean IsEmpty(Queue *q){
return (q->front==NULL && q->rear==NULL);
}
void insert(QueueElement x,Queue *q){
Node *np;
np=(Node*)malloc(sizeof(Node));
if(np==NULL){
printf("Not enough memory\n");
q->full=TRUE;
}
else{
np->entry=x;
np->next=NULL;
if(IsEmpty(q))
q->front=q->rear=np;
else{
q->rear->next=np;
np=q->rear;
}
++q->count;
printf("Inserted %d\n", x);
}
}
void Remove(Queue *q){
Node *np;
if(IsEmpty(q))
printf("Queue is empty\n");
else{
q->count--;
int x=q->front->entry;
np=q->front;
q->front=q->front->next;
if(q->front==NULL)
q->rear=NULL;
free(np);
printf("Removed %d\n",x);
}
}
void display(Queue q){
//if(IsEmpty(q))
// printf("Queue is empty\n");
Node *iter = q.front;
while(iter) {
printf("%d ", iter->entry);
iter = iter->next;
}
}
int main()
{
Queue q;
createQueue(&q);
Remove(&q);
insert(1,&q);
insert(2,&q);
insert(3,&q);
insert(4,&q);
Remove(&q);
display(q);
return 0;
}
My display function is as follows:我的显示功能如下:
void display(Queue q){
//if(IsEmpty(q))
// printf("Queue is empty\n");
Node *iter = q.front;
while(iter) {
printf("%d ", iter->entry);
iter = iter->next;
}
}
The comments already spotted the problem, but just to give this an answer:评论已经发现了问题,但只是为了给这个答案:
In the insert
function the following line is the problem:在
insert
函数中,以下行是问题所在:
np=q->rear;
Should be:应该:
q->rear=np;
Which works as expected:按预期工作:
Queue is empty
Inserted 1
Inserted 2
Inserted 3
Inserted 4
Removed 1
2 3 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.