Pointers 队列实现引发不兼容的指针类型错误
我想我缺少关于结构和指针的一般概念。因此,下面的代码产生了2个警告/错误,我不明白为什么Pointers 队列实现引发不兼容的指针类型错误,pointers,struct,queue,Pointers,Struct,Queue,我想我缺少关于结构和指针的一般概念。因此,下面的代码产生了2个警告/错误,我不明白为什么 为什么“queue->head=temp”会产生以下警告: 警告:不兼容指针类型的分配[默认启用] 为什么“queue->tail->next=temp”会产生以下错误: 错误:取消引用指向不完整类型的指针 注意:行“Node*temp=newNode(data)”不会抛出任何错误/警告,因此它是成功的 typedef struct { int data; struct Node *next; }
typedef struct {
int data;
struct Node *next;
} Node;
typedef struct {
struct Node *head;
struct Node *tail;
} Queue;
void enQueue(Queue *queue, int data)
{
// Create a new node
Node *temp = newNode(data);
// If queue is empty, then new node is both head and tail
if (queue->tail == NULL)
{
queue->head = temp;
queue->tail = temp;
return;
}
// Add the new node at the end of queue and change tail
queue->tail->next = temp;
queue->tail = temp;
}
你是如何编译这段代码的? 您的
节点
结构包含指向另一个节点
的指针。按照您声明结构的方式,编译器在解析结构定义时不知道节点
。因此,你必须写:
1 typedef struct Node{
2 int data;
3 struct Node *next;
4 } Node;
这样,编译器就知道在解析结构时如何处理它。在第3行中,它已经知道节点
是结构。由于缺少一些代码,我创建了一个实现超级简单队列的最小示例:
#include <stdlib.h>
#include <stdio.h>
#define MAX 5
typedef struct Node{
int data;
struct Node *next;
} Node;
typedef struct {
struct Node *head;
struct Node *tail;
} Queue;
Node* newNode(const int nodeData){
Node* tmp = malloc(sizeof(*tmp));
if (NULL == tmp){
printf("Could not allocate Node ... exiting");
exit(EXIT_FAILURE);
}
tmp->data = nodeData;
tmp->next = NULL;
return tmp;
}
void enQueue(Queue *queue, int data)
{
// Create a new node
Node *temp = newNode(data);
// If queue is empty, then new node is both head and tail
if (queue->tail == NULL)
{
printf("Queue is empty\n");
queue->head = temp;
queue->tail = temp;
return;
}
// Add the new node at the end of queue and change tail
queue->tail->next = temp;
queue->tail = temp;
}
void printQueue(Queue* q){
Node* tmp = q->head;
while (tmp != NULL){
printf("Value: %d\n", tmp->data);
tmp = tmp->next;
}
}
int main(void){
Queue q;
q.head = q.tail = NULL;
int i;
for (i = 0; i < MAX; ++i){
printf("%d is entered into the queue\n", i);
enQueue(&q, i);
}
printQueue(&q);
}
#包括
#包括
#定义最大值5
类型定义结构节点{
int数据;
结构节点*下一步;
}节点;
类型定义结构{
结构节点*头部;
结构节点*尾部;
}排队;
Node*newNode(const int nodeData){
节点*tmp=malloc(sizeof(*tmp));
如果(NULL==tmp){
printf(“无法分配节点…正在退出”);
退出(退出失败);
}
tmp->data=nodeData;
tmp->next=NULL;
返回tmp;
}
无效排队(队列*队列,整数数据)
{
//创建一个新节点
Node*temp=newNode(数据);
//若队列为空,那个么新节点既是头节点又是尾节点
如果(队列->尾部==NULL)
{
printf(“队列为空\n”);
队列->头部=临时;
队列->尾部=临时;
返回;
}
//在队列末尾添加新节点并更改尾部
队列->尾部->下一步=临时;
队列->尾部=临时;
}
无效打印队列(队列*q){
节点*tmp=q->head;
while(tmp!=NULL){
printf(“值:%d\n”,tmp->data);
tmp=tmp->next;
}
}
内部主(空){
队列q;
q、 head=q.tail=NULL;
int i;
对于(i=0;i
Stackoverflow记录对原始帖子的编辑。为了避免任何混乱,在回复出现之前,我不会再对原始帖子进行编辑。我只是想明确提到这一点。提前谢谢。