【问题标题】:How does this print function moves pointer to next item in the linked list?这个打印函数如何将指针移动到链表中的下一项?
【发布时间】:2023-03-18 05:04:01
【问题描述】:
struct ll {
    int num;
    struct ll *next;
};

struct ll *head;

main() {
    /* code to assign head pointer some memory */

    print(head->next);
}

我读到上面代码中的print() 函数将指针移动到下一项。这如何将头指针移动到下一项?

【问题讨论】:

    标签: c function pointers recursion


    【解决方案1】:

    print() 必须类似于:

    print(struct ll *foo) {
      // code
      head = head->next;
      // other code
    }
    

    请注意,这在很多方面都不是好的代码,但这就是它将head 移动到下一个项目的方式。

    【讨论】:

    • head 在您的代码中未定义?也许你的意思是 foo->head = foo->head->next;
    • @Daniel 实际上,他的意思可能是foo = foo->next;
    • @Daniel: head 在 OP 的代码中被定义为全局变量。
    【解决方案2】:

    您的head 指针是一个全局指针,您不想在简单地遍历列表时更改它。这将遍历列表并打印每个 num 字段。

    void print(struct ll *node) {
        while (node) {
            printf("%d\n", node->num);
            node = node->next;
        }
    }
    
    main() {
        /* code to assign head pointer some memory */
        print(head);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 2012-07-19
      • 2011-01-05
      相关资源
      最近更新 更多