我尝试使用以下结构使用链表实现队列。但是在入队函数中,就在评论下方,我收到了上述错误。此错误已发生,同时在此链接给出的代码中使用了相同的代码 http://quiz.geeksforgeeks.org/queue-set-2-linked-list-implementation/ .有一条评论是我用来运行代码的。但我不明白为什么我会收到此错误。请帮忙!
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct queue
{
struct queue *front;
struct queue *rear;
};
struct queue* createQueue();
void enqueue(struct queue *q,int info);
int dequeue(struct queue *q);
void display(struct queue *q);
int isEmpty(struct queue *q);
void menu();
struct queue* createQueue()
{
struct queue *new_queue;
new_queue = (struct queue*) malloc(sizeof(struct queue));
if(new_queue != NULL)
{
return ;
}
new_queue->front = new_queue->rear = NULL;
return new_queue;
}
int isEmpty(struct queue *q)
{
if(q->front == NULL)
return 1;
}
void enqueue(struct queue *q,int info)
{
struct node *temp,*temp1;
temp = (struct node*) malloc(sizeof(struct node));
if(temp == NULL)
return ;
temp->data = info;
temp->next = NULL;
if(q->front == NULL && q->rear == NULL)
{
q->front = temp;
q->rear = temp;
}
if(q->rear != NULL)
{
//temp1 = q->rear;
q->rear->next = temp;
q->rear = temp;
}
}
int dequeue(struct queue *q)
{
if(isEmpty(q) == 1)
{
printf("Empty list!");
}
struct node *temp = q->front;
q->front = temp->next;
int data = temp->data;
free(temp);
return (data);
}
void display(struct queue *q)
{
struct node *start,*end = NULL;
start = q->front;
end = q->rear;
if(isEmpty(q) == 1)
{
printf("Empty List!");
}
while(start != NULL)
{
printf("%d",start->data);
start = start->next;
}
}
void menu()
{
int choice = 0;
int input = 0;
struct queue *q;
while(1)
{
printf("\t\tMain Menu\n");
printf("\t0.Create Queue\n");
printf("\t1.Enqueue\n");
printf("\t2.Dequeue\n");
printf("\t3.Display\n");
printf("\t4.Exit\n");
printf("\tEnter the desired choice:");
scanf("%d",&choice);
switch(choice)
{
case 0:
q = createQueue();
break;
case 1:
printf("\tEnter the data:");
scanf("%d",&input);
enqueue(q,input);
break;
case 2:
printf("%d",dequeue(q));
break;
case 3:
display(q);
break;
case 4:
exit(0);
default:
printf("\tThe value is invalid!");
}
}
}
int main()
{
menu();
return 0;
}
最佳答案
你在写
q->rear->next = temp;
rear
是一个 queue
结构,而不是一个 node
结构。
你写了这个:
struct queue
{
struct queue *front;
struct queue *rear;
};
但从你使用的术语来看,我认为它应该是这样的:
struct queue
{
struct node *front;
struct node *rear;
};
(当然错误行会变得正常,但你可能还有其他问题:))
关于c - 'struct queue' 没有名为 'next' 的成员。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39178493/