首页 > 解决方案 > 实现递归函数的问题

问题描述

对于家庭作业,我得到了带有指令的代码来实现一个递归函数,该函数在 main 列表中的下一个节点上调用自身,除非当前节点为 NULL 或当前节点的值等于“目标”

我最近的尝试是下面代码的围栏部分。我可以让它打印 0,但这不是整个列表。我不确定我做错了什么,因为我对链表和节点没有太多经验。

typedef struct node {
  struct node* next;
  unsigned short index;
  char* value;
} node;

node* create_node(unsigned short index, char* value) {
  node* n = malloc(sizeof(node));
  n->value = value;
  n->index = index;
  n->next = NULL;
  return n;
}

node* create_nodes(char* values[], unsigned short index, unsigned short num_values) {
  if(num_values == 0) {
    return NULL;
  }

  node* n = create_node(index, values[0]);

  n->next = create_nodes(values + 1, index + 1, num_values - 1);
  return n;
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
node* find_match(node* cur, char* target) {
  if(cur == NULL){
    return NULL;
  }
    if(cur->value != NULL){
      node* result = create_node(cur->index, cur->value);
      result->next = find_match(cur->next, cur->value);
    }else{
    return find_match(cur->next, cur->value);
    }
  }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

int main() {
  char* values[] = {
    "foo", // 0
    "bar", // 1
    "baz", // 2
    "duh", // 3
    "dunk", // 4
    "derp" // 5
  };

  node* head = create_nodes(values, 0, 6);

  node* target = find_match(head, "dunk");

  printf("%d\n", target->index);

  return 0;
}

没有给出错误消息,除了我已经“修复”的先前分段错误,但我认为它应该打印整个列表。

标签: crecursionlinked-list

解决方案


您可以一次插入一个元素并使用循环发送每个元素,因为您知道数组的大小。然后您只需对代码进行少量更改。

struct linkList {
       int data;
       linkList* next;
  }node;

 node create(int val){
       node tmp;
       tmp = (node)malloc(sizeof(struct linkList));
       tmp->data = val;
       return tmp;
  }
 node* insertNodeAtHead(linkList* llist,int data) {
        node tmp;
        tmp = create(data);
        tmp->next = llist;
        return tmp;
     }

然后您可以使用您的 Key 进行搜索,就像打印 List 中的所有元素一样

void print(linkList* head) {
     while(head !=NULL){
     printf("%d\n",head->data); // check here is this your key or Not 
     head = head->next;
   }
 } 

但是这个问题是已知的,在发布任何问题之前,请确保您尝试在 Google 中进行足够的搜索!希望你得到这个想法并以你自己的方式实现它。


推荐阅读