【问题标题】:Creating a linked list from nodes that already have been created. Getting Seg Fault从已经创建的节点创建一个链表。获得 Seg 错误
【发布时间】:2014-12-04 08:32:30
【问题描述】:

所以这对于我所在的课程来说是个问题。规定我们使用下面的代码作为我们的主要不编辑它

int main(void) {

  // a reference to the head of our list
  node *head = NULL;
  node ** list = &head;

  // the nodes we will put in our list
  node a = {6,NULL};
  node b = {8,NULL};
  node c = {4,NULL};
  node d = {10,NULL};
  node e = {2,NULL};

  // build the list
  append(list, &a);
  append(list, &b);
  prepend(list, &c);
  append(list, &d);
  prepend(list, &e);

  // print the list
  print(list);

  // test the find function
  int value;
  for (value = 1; value <= 10; value++) {
    node * found = find(list, value);
    if (found == NULL)
      printf("Node %d not found...\n", value);
    else
      printf("Found node %d!\n", found->content);
  }

  // test delete function
  delete(list, 4);
  delete(list, 8);
  print(list);

  return 0;
}

我们需要自己创建 main 中使用的所有函数。目前正在处理附加功能。有人告诉我 append 函数应该是这样的:append(node * list, node * new_node);

tydef stuct node_t {
  int content;
  struct node_t *next;
} node;

这就是我的节点声明。

void append(node ** list, node * new_nodes) {
  node ** current = list;
  while ((*current)->next != NULL) {
    (*current) = (*current)->next;
  }
  (*current)->next = new_node;
  list = current;
}

这是我的附加功能。我相对确定最后一行是错误的,但我一开始就不知所措。任何想法或建议都会很棒。

【问题讨论】:

  • 最好的办法是绘制节点图,并在阅读代码时仔细更改图上的指针。

标签: c linked-list nodes


【解决方案1】:

考虑这两行:

node *head = NULL;
node ** list = &head;

这使得list 指向一个指向NULL 的指针。

然后考虑:

append(list, &a);

和(来自append 函数):

node ** current = list;
while ((*current)->next != NULL) {

您将指向NULL 的指针传递给append 函数,这意味着*current 是指向NULL 的指针,然后您取消引用指向undefined behaviorNULL 指针还有你的崩溃。

【讨论】:

  • 罗杰。所以我需要将指针指向 &a,因为它是我唯一的位置,并将其设置为头部。还要确保我们在列表的末尾以供将来追加?
【解决方案2】:

由于list是按值传递的,所以可以把它当做临时变量:

void append(node **list, node *new_node)
{
    while(*list != NULL)
        list = &((*list)->next);
    *list = newNode;
}

【讨论】:

  • 谢谢。通过一点工作,这让我开始了。我没有足够的声望来投票给你。我很抱歉。
【解决方案3】:

head 和 list 尚未设置 - 如果 list == NULL,您必须先检查。

void append(node ** list, node * new_nodes) {
   node **current = list;
   if (*current == NULL) {
       *current = node;
       return;
   }
   while ((*current)->next != NULL) {
      (*current) = (*current)->next;
   }
   (*current)->next = new_node;
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多