簡體   English   中英

C中的遞歸鏈表

[英]Recursive linked list in C

我剛剛嘗試在C中實現一個遞歸鏈表附加,並且由於某種原因,無論我做什么,我都會保持NULL,即使我在遇到NULL值時也是malloc。

以下代碼不打印任何內容。 有任何想法嗎?

#include <stdlib.h>
#include <stdio.h>

typedef struct node {
  unsigned v;
  struct node* next;
} node;

void insert(unsigned x, node* l) {
  if (l == NULL){
    node* new_node = (node*)malloc(sizeof(node));
    new_node->v = x;
    new_node->next = NULL;
    l = new_node;
  }
  else {
    insert(x, l->next);
  }
}

void print(node *l) {
  if (l == NULL) return;
  printf("%d\n", l->v);
  print(l->next);
}

int main(){

  node* l = NULL;
  insert(1, l);
  insert(2, l);

  print(l);

  return 0;
}

非常感謝。

編輯:即使我初始化它,它仍然是相同的。

首先,您將按值傳遞給函數,這樣您就不會看到任何更改。 目前,當您將l設置為new_node時,只更改方法插入中的l的本地值。 您可能希望修改函數以返回l並將main中的l設置為此函數的返回值。

node *insert(int x, node *l){
  //.... your method
  return l;
}

主要:

node *l = NULL;
l = insert(1, l);
l = insert(2, l);

其次,出於同樣的原因,您的遞歸調用不會將節點附加到LL。 改變對此的調用:

 l->next = insert(x, l);
#include <stdlib.h>
#include <stdio.h>

typedef struct node {
unsigned v;
struct node* next;
} node;

node* insert(unsigned x, node** ll) {
  if (*ll == NULL){
*ll = (node*)malloc(sizeof(node));
(*ll)->v = x;
(*ll)->next = NULL;

  }
  else {
    insert(x, &(*ll)->next);
}
}

void print(node *l) {if (l == NULL) return;
printf("%d\n", l->v);
print(l->next);
}

int main(){

node* l = NULL;
insert(1, &l);
insert(2, &l);
print(l);

return 0;
}

編譯沒有gcc沒有開關

輸出:1 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM