【发布时间】:2014-04-20 05:16:39
【问题描述】:
我尝试使用链表来实现队列,但总是出现错误:赋值和赋值中的不兼容类型使得指针从整数而不进行强制转换。
这是我的代码:
#include <stdlib.h>
#include <stdio.h>
#include "Queue.h"
struct QUEUE_ELEMENT{
int element;
struct QUEUE_ELEMENT *next;
};
int size;
struct QUEUE_ELEMENT *head, *tail;
void initQueue(){
head = NULL;
tail = NULL;
size = 0;
} // void initQueue()
int queueEmpty(void) {
return (head == NULL && tail == NULL);
} // int queueEmpty(void)
int enqueue(QUEUE_ELEMENT e) {
struct QUEUE_ELEMENT *temp;
if (tail == NULL){
tail -> next = NULL;
tail -> element = e;
head = tail;
}
else {
temp = malloc(sizeof(QUEUE_ELEMENT));
tail -> next = temp;
temp -> element = e;
temp -> next = NULL;
tail = temp;
}
return size++;
} // int enqueue(QUEUE_ELEMENT e)
int dequeue(QUEUE_ELEMENT *e){
struct QUEUE_ELEMENT *temp;
temp = malloc(sizeof(QUEUE_ELEMENT));
if (queueEmpty() != 0 ){
temp = head;
if(temp -> next != NULL){
temp = temp -> next;
free(head);
head = temp;
}
else{
free(head);
head = NULL;
tail = NULL;
}
}
return size--;
} // int dequeue(QUEUE_ELEMENT *e)
我修改了很多代码。
为什么是'tail -> element = e;'在 enqueue() 中发生错误“分配中的类型不兼容”?我该如何解决?
【问题讨论】:
-
在哪里???发布实际的编译器错误
-
那个带有
size、head、tail、和next的“节点”看起来不是一个好的设计.. -
这段代码的bug太多了,看得我头疼……为什么一个简单的链表需要这么多指针?
-
在每个作用域中,您都在分别创建链表。永不解脱。大量内存泄漏,函数范围之间没有恢复。
-
This:
if (tail == NULL) { tail -> next = NULL; ...只是此代码中 未定义行为 重复实例的一个示例。在你对指针在 C 中的工作方式有一个合理的理解之前,这个任务将是你的撤销。
标签: c linked-list queue