【问题标题】:Linked List quetion [closed]链表问题[关闭]
【发布时间】:2016-05-19 10:01:08
【问题描述】:

在下面的代码 sn-p 中,count 函数计算创建的链表中的节点数。我想知道下一个地址是如何从count(C_list->next);函数调用传递过来的?

struct linked_list
{
 int number;
 struct linked_list *next;
};
typedef struct linked_list node;

main()
{
    head = (node*)malloc(sizeof(node));
    create(head);
    print(head);
    c = count(head);
}
int count(node* C_list)
{
    if(C_list->next==NULL)
      return(0);
    else
    {
      return(1+count(C_list->next));//How does the next address gets passed from this function call?
    }
}

【问题讨论】:

  • 你在问这个(递归)是如何工作的吗?您的代码已经发送了下一个地址。你的程序的输出是什么?
  • 请注意,这是一种非常低效的混淆计算链表节点的方法。专业代码不会使用递归,而是使用普通循环。递归几乎总是解决实际编程问题的一种非常糟糕的方法。

标签: c singly-linked-list


【解决方案1】:
main()
{
    head = (node*)malloc(sizeof(node));
    create(head);
    print(head);
    c = count(head);         //See here you are sending the actual node, which is head.
}
int count(node* C_list)
{
    if(C_list->next==NULL)   //-->Here the if condition is checking for the next node (head->next) whether it is null or not.
      return(0);            //-->If the next node is null, it means no nodes are there. So returning 0.
    else
    {
      return(1+count(C_list->next));
    }
}

现在棘手的部分是返回行,您将在其中将C_list->nexthead->next 传递给计数函数。现在在递归之后,在上面的if 条件下,它检查下一个节点地址,即head->next->next,它一直持续到节点是null,这样下一个地址就被传递给递归函数。希望这可能对您有所帮助。

【讨论】:

  • 非常感谢您的澄清!
【解决方案2】:

首先,我必须建议您阅读一本关于 C 的书,因为您的问题似乎是“显而易见的”。所以这是我书中的一部分:

对函数调用中的表达式C_list->next 求值,并将结果作为参数传递给函数。

表达式采用C_list 变量(一个指针),解除对它的引用,然后采用next 成员。 next 的值指向列表的下一个节点,然后作为参数传递给函数。

函数现在继续下一个节点。

【讨论】:

  • 非常感谢您的澄清!
猜你喜欢
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
相关资源
最近更新 更多