【问题标题】:What is the output of the following program? How do you trace such a program?以下程序的输出是什么?你如何跟踪这样的程序?
【发布时间】:2016-07-03 22:46:54
【问题描述】:

我必须确定下面程序的输出。答案是B E A D C,但我不确定如何跟踪程序。这是我所知道的:

我们首先声明一个名为road_trip 的结构,其数据类型为trip。在主程序中,我们为成员place 赋值。然后创建一个链表,其中起始节点为s2,结束节点为s3。因为您可以看到起始节点的地址存储在一个单独的指针ptr 中,通常称为头指针。 s3 是链表的结尾,因为如果您看到s3,您可能会注意到s3nextNULL。这意味着s3 没有引用任何其他节点。

我不明白的是程序如何打印存储在s2B)、s5E)、s1A)、s4D) 和 s3 (C) 的顺序。我确定这与我写 cmets 之后的两行有关。解释会很有帮助。

#include <stdio.h>

typedef struct road_trip
{
    char place;
    struct road_trip* next;
}trip;

int main (void)
{
    trip s1, s2, s3, s4, s5, s6;
    trip *ptr;

    s1.place = 'A';
    s2.place = 'B';
    s3.place = 'C';
    s4.place = 'D';
    s5.place = 'E';

    s5.next = &s1;
    ptr = &s2;
    s1.next = &s4;
    s3.next = NULL;
    s4.next = &s3;
    s2.next = &s5;

    while (ptr != NULL)
    {
        printf("%c ", ptr -> place);    /*I don't get this line*/
        ptr = ptr -> next;    /*I don't get this line*/
    }
    return 0;
}

【问题讨论】:

  • 我投票决定将此问题作为题外话结束,因为您可以简单地运行它并查看自己是否合适。
  • 它被称为“链表”。 "next" of s3 is NULL - 这就是为什么'C'是最后一个被打印的。
  • “你如何跟踪这样的程序” - 与任何其他程序相同。但是你必须先了解指针,而你显然没有。
  • '输出是什么'。你有没有尝试过任何非常简单的事情,比如运行程序?

标签: c linked-list structure


【解决方案1】:
printf("%c ", ptr -> place);    /*I don't get this line*/
ptr = ptr -> next;    /*I don't get this line*/
  • 这里,ptr 是指向trip 的指针(即 struct road_trip
  • 当您想使用指针访问结构的成员时,使用-&gt;Structure dereference 运算符)运算符

答案是“B E A D C”,但我不确定如何跟踪程序。

s5.next = &s1;
ptr = &s2;
s1.next = &s4;
s3.next = NULL;
s4.next = &s3;
s2.next = &s5;

以上部分代码对跟踪程序很有用...

这里

  • ptr 指向 s2

和:

  • next s2 的成员指向 s5
  • next s5 的成员指向 s1
  • next s1 的成员指向 s4
  • next 的成员 s4 指向 s3
  • next s3 的成员指向 NULL

您在问题中给出了正确的解释


我不明白的是程序如何打印存储在s2 (B)、s5 (E)、s1 (A)、s4 (D) 和 @987654352 中的值@ (C) 按此顺序

现在,当您以这种方式使用 ptr 进行迭代时:

while (ptr != NULL)
{
    printf("%c ", ptr -> place);
    ptr = ptr -> next;
}

跟踪循环:

  • 第一次迭代上打印B,因为ptr指向s2,因此ptr-&gt;places2.place相同(所以使用@987654322 @ 操作place 成员的值访问)
  • 那么ptr = ptr-&gt;nextptr = s2-&gt;next 相同,因此ptr = &amp;s5 因为s2-&gt;next 指向s5

  • 同样,这个循环继续下去,你会得到他们next成员连接方式的输出

  • 打印s3后循环结束,因为s3-&gt;next指向NULL,因此ptr在打印s3后变为=NULL


进一步阅读:

  • 这是linked lists的典型实现(点击了解更多)

  • 这种类型的列表,其中一个结构成员指向列表的下一个结构,称为 singly linked list (点击了解更多)

【讨论】:

    【解决方案2】:

    ptr 是指向 s2 的指针,因此显示 char ptr->place 将显示行程 s2 的地点。然后 ptr 被更改为下一个指针 - s2 的下一个是 s5。显示 ptr -> place 现在将显示行程 s5 的地点。然后ptr变为s5的next,即s1,一直到s3,next指针为NULL。

    【讨论】:

      猜你喜欢
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      相关资源
      最近更新 更多