C LinkedList 不会工作

C LinkedList won't work

我已经尝试用 C 构建自己的 LinkedList 几个小时了,但我无法使其正常工作。请指出此代码出错的位置和原因。对于实际行为向下滚动到 'main'.

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' 似乎确实以某种方式改变了传递的列表,使得只有最后一个元素保留在那里。我已经多次重写程序 - 递归和迭代 - 结果似乎总是这样。

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
}

我什至用其他语言重新创建了该程序,以查看程序中是否存在任何突破性的逻辑缺陷,但在其他地方我立即让它运行。

在您的程序中,您正在搜索最后一个元素:

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;

看起来你需要决定是要添加到头部还是尾部......看起来你有点想添加到头部,但是你会把下一个设为当前而不是空...

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;