【问题标题】:traverse pointer from last node to first从最后一个节点到第一个节点的遍历指针
【发布时间】:2015-10-14 13:44:26
【问题描述】:
bn_ptr drive_temp(bn_ptr head,bn_ptr temp,bn_ptr current)
{

    while(temp->next!=current)
    {
        temp=temp->next;
        current=temp;
    }
    temp=head;

    return current; 
}

我有链表和'head'指针保存第一个节点,'current'指针保存最后一个节点,我想将'current'一个一个带到head,所以我编写了这个函数,但是在我调试时它给出了分段错误程序

【问题讨论】:

  • while(temp->next!=current) 应该是 while(temp && temp->next!=current),否则您将取消引用 NULL 指针,这是未定义的行为。
  • 没有一种非常方便的方法可以向后遍历单链表...您可以改用双链表,或者先反转列表,然后向前遍历反转的列表。
  • mch 我试过你的答案,但没有解决,我不想反转列表谢谢你的回答
  • 将“temp”作为参数有什么意义?
  • 我是新学的,温度不一定,谢谢@SelçukCihan

标签: c


【解决方案1】:

temp->next!=current 永远不会为真,除非temp==temp->next

试试这个:

bn_ptr drive_temp(bn_ptr head,bn_ptr temp,bn_ptr current)
{

    while(temp->next!=current)
    {
        temp=temp->next;
    }
    current=temp; /* get this out of the loop */
    temp=head;

    return current; 
}

或更简化:

bn_ptr drive_temp(bn_ptr head,bn_ptr temp,bn_ptr current)
{
    (void)head; /* head isn't used, so put this to avoid warning */
    while(temp->next!=current)
    {
        temp=temp->next;
    }
    /* current and temp will be lost, so assigning to them here is useless */

    return temp; 
}

为了更安全,请确保temp 不是NULL,以避免current 无效时出现运行时错误。

bn_ptr drive_temp(bn_ptr head,bn_ptr temp,bn_ptr current)
{
    (void)head; /* head isn't used, so put this to avoid warning */
    while(temp != NULL && temp->next!=current)
    {
        temp=temp->next;
    }

    /* temp will be the previous node of current or NULL */
    return temp; 
}

也许你想要这个:

bn_ptr drive_temp(bn_ptr head,bn_ptr current) /* remove temp from the arguments */
{
    bn_ptr temp = head;
    while(temp != NULL && temp->next!=current)
    {
        temp=temp->next;
    }

    /* temp will be the previous node of current or NULL */
    return temp; 
}

【讨论】:

  • @ameyCU 不应该。投射到void 游戏我no errors nor warnings,投射到void* 给了我a warning
  • 这只是未使用变量的警告。但我很惊讶它没有给 void 提供任何东西。
  • @ameyCU 尽管有警告,为什么演员应该 void *?为什么您想要警告?
  • @MikeCAT 我很感谢你,你的代码很好用,谢谢 ameyCU
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-09
相关资源
最近更新 更多