我正在尝试在C中构建我自己的LinkedList几个小时,我只是无法让它正常工作。请指出此代码出错的位置和原因。对于实际行为,请向下滚动到“主要”。
struct List {
struct Node * head;
} list;
struct Node {
int data;
struct Node * next;
} node;
void
add(struct List* list, int z){
//add as first element
if(list -> head == NULL){
list -> head = malloc(sizeof(struct Node));
(list -> head) -> data = z;
(list -> head) -> next = NULL;
return;
}
//add to tail
struct Node * curr = list -> head;
while((curr -> next) != NULL){
curr = curr -> next;
}
list -> head = malloc(sizeof(struct Node));
(list -> head) -> data = z;
(list -> head) -> next = NULL;
return;
}
void
printNode(struct Node * node){
if(node == NULL){
printf("NULL\n");
return;
}
printf("%d -> ", node->data);
printNode(node->next);
}
void
printList(struct List * list){
if(list->head == NULL)
printf("empty\n");
else
printNode(list->head);
}
出于某种原因,似乎'add'确实改变了传递的List,只有最后一个元素保留在那里。我已经多次重写程序 - 递归和迭代 - 结果似乎总是如此。
int
main(){
struct List myList;
myList.head = NULL;
printList(&myList); // empty
add(&myList, 1);
printList(&myList); // 1 -> NULL
add(&myList, 2);
printList(&myList); // 2 -> NULL, should be 1 -> 2 -> NULL
add(&myList, 3);
printList(&myList); // 3 -> NULL, should be 1 -> 2 -> 3 -> NULL
add(&myList, 4);
printList(&myList); // 4 -> NULL, should be 1 -> 2 -> 3 -> 4 -> NULL
}
我甚至用其他语言重新创建了该程序,看看程序中是否存在任何突破性的逻辑缺陷,但在其他地方我立即开始工作。
答案 0 :(得分:1)
在你的程序中,你正在搜索最后一个元素:
while((curr -> next) != NULL){
curr = curr -> next;
}
这是正确的,但是你正在改变头脑:
list -> head = malloc(sizeof(struct Node));
(list -> head) -> data = z;
(list -> head) -> next = NULL;
相反,您应该创建一个新元素并更改当前结束的next
指针:
struct Node *new_data = malloc(sizeof(struct Node));
new_node -> data = z;
new_node -> next = NULL;
curr -> next = new_node;
答案 1 :(得分:1)
看起来你需要决定是否要添加到头部或尾部...看起来你有点想要添加到头部,但是那样你会做下一个当前而不是空...
list -> head = malloc(sizeof(struct Node));
(list -> head) -> data = z;
(list -> head) -> next = NULL; // HERE <-- next is NULL
而不是:
list -> head = malloc(sizeof(struct Node));
(list -> head) -> data = z;
(list -> head) -> next = curr;