【问题标题】:How to iterate over linked list (c)如何迭代链表(c)
【发布时间】:2021-08-14 16:40:25
【问题描述】:

一个名为node 的简单链表数据类型包含一个数字和一个指向下一个节点的指针

变量 x 用于scanf 从用户输入中捕获值

一个数组arr 用于保存指向所创建节点的指针

指向起始节点start_ptr的指针

第一个循环捕获用户输入,然后将其附加到节点并移动到下一个节点 然后将该节点的指针添加到arr

最后一个循环简单地循环从第一个节点开始的节点并打印从用户输入中捕获的每个数字

typedef struct node 
{
    int n;
    struct node *next ;
}
node;

int main(void)
{
    // variable to hold integers 
    int x ; 
    node arr[3];
    node *start_ptr;
    node *p = malloc(sizeof(node));
    // check if memory allocated for node 
    if (p == NULL)
    {
        return 1;
    }
    start_ptr = p;
    for (int i =0; i < 3; i++)
    {
        scanf("%i" , &x);
        p->n = x;
        p->next = realloc(p , sizeof(node));
        arr[i] = *p;
    }
    for (  node *tmp = start_ptr ; tmp != NULL; tmp = tmp->next)
    {
        printf("%i", tmp->n);
    }
    return 0;
}

怎么了

当您运行代码时,它会从用户那里接受三个数字,然后开始打印最后一个数字,直到它崩溃或您终止程序

谁能解释为什么第二个循环不能正常工作

【问题讨论】:

  • realloc(p , sizeof(node)); 是错误的。你为什么要这样做?
  • @n.1.8e9-where's-my-sharem。你能说清楚一点吗
  • 如果你想要一个列表,为什么要分配一个数组?
  • @vonbrand 我使用 arr 检查数字
  • 最后一个节点的next字段没有设置为NULL

标签: c pointers


【解决方案1】:

遍历列表的代码是正确的。问题都在第一个for循环中:

  1. 最后一个节点的next指针未设置为NULL。
  2. 当你应该使用malloc时,你使用realloc
  3. 您没有将p 设置为循环结束时的下一个元素。

你想要这个:

  ...
  start_ptr = p;
  for (int i = 0; i < 3; i++)
  {
    scanf("%i", &x);
    p->n = x;

    if (i == 3 - 1)     // set next to NULL for the last element
      p->next = NULL;   
    else
      p->next = malloc(sizeof(node));  // otherwise allocate memory for next element

    p = p->next;        // set p to next element
  }
  ...

您不需要arr 数组。为了调试你的代码,你最好使用你的调试器。

完整的程序:

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
  int n;
  struct node* next;
}
node;

int main(void)
{
  // variable to hold integers 
  int x;
  node* start_ptr;
  node* p = malloc(sizeof(node));   // check if malloc returns NULL
                                    // not necessary in toy programs
  start_ptr = p;
  for (int i = 0; i < 3; i++)
  {
    scanf("%i", &x);
    p->n = x;

    if (i == 3 - 1)     // set next to NULL for the last element
      p->next = NULL;
    else
      p->next = malloc(sizeof(node));  // otherwise allocate memory for next element

    p = p->next;        // set p to next element
  }

  for (node* tmp = start_ptr; tmp != NULL; tmp = tmp->next)
  {
    printf("%i", tmp->n);
  }
  return 0;
}

这段代码远非完美,它只是纠正了初始代码中的错误。仍有进一步改进的空间。

【讨论】:

  • 我使用了你的 sn-p 并遇到了 seg 错误
  • 代码sn-p是正确的,你做错了。
  • 我不明白我做了什么导致我的代码损坏
  • @katysha 没有看到你的代码没人知道。
  • 理论上,您应该在使用x 中的值之前检查scanf() 的返回值——实际上,当OP 遇到基本问题时,这是不必要的。不过,最好提一下(并且此评论可能足以说明答案不需要更改)。在循环中不检查 malloc() 的结果是不那么可辩的。
猜你喜欢
  • 2013-10-29
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多