【问题标题】:How To Create a Linked List in Ascending Order如何按升序创建链表
【发布时间】:2013-10-31 18:39:34
【问题描述】:

我得到一个名为“head”的稀疏数组,它是具有索引和值的二维数组。所以像: (3, 100) (6,200) (8,100)

  1. 我必须按升序将一个节点(值、索引)插入到这个稀疏数组中。因此,如果给我 (2,100),则列表应如下所示: (2, 100) (3,100) (6,200) (8,100)

同样,如果给我 (4,200),它应该返回 (3,100) (4,200) (6,200) (8,100)

条件1:如果索引相同,那么我必须添加值

所以如果给我 (3,100),那么我应该返回 (3,200) (6,200) (8,100)

条件2:如果索引相同,并且值为零,则应该删除该值。所以如果数组是(3,-100),我必须返回

(6,200) (8,100)

Node * List_insert_ascend(Node * head, int value, int index)
{
  Node * node = List_create(value, index); //this creates an empty node, "node"

  if (index < (head->index)) //node's index is less, e.g. (1,100)
    {node -> next = head;} //this inserts "node" before "head"
  if (index == (head->index))
  {
    node = head;
    head->value = head->value + value; //Condition 1
    while ((head->value)==0)  //Condition 2
    {
      Node *p = head->next;
      head = p;
        
    }
  }
  return node;

}

我的理解是,当我做 head->next 新的 head 时,应该去掉原来的条目。

但是 0 值索引继续保留在列表中。结果是 (3,0) (6,200) (8,100)

如果有人可以帮助我找出我做错了什么(甚至可能是为什么),我将不胜感激。

【问题讨论】:

  • 在 List_insert_ascend 方法中,您将获得指向列表头节点的指针。因此,作为第一步,您实际上必须遍历列表中的节点以查看哪个节点具有匹配的索引。如果没有节点具有匹配的索引,则创建一个新节点。如果特定节点确实具有相同的索引,则将该节点的值与 List_insert_ascend 中的给定值相加。现在检查结果值是否为 0。如果是,则删除该节点。在整个方法结束时,您应该返回结果列表的头部,而不是任意节点。

标签: c struct linked-list structure sparse-array


【解决方案1】:

您的代码中有未定义的行为。

当你这样做时

Node *p = head->next;
head = p;
free(p);

您实际上正在释放 headp 指向的节点。然后取消引用 head 会导致未定义的行为。

但这不是唯一的问题。另一个是您实际上并没有取消链接您正在释放的节点。之前的 head-&gt;next(在重新分配 head 及其后续释放之前)指针仍然指向现在空闲的节点。

【讨论】:

  • 谢谢,我刚刚摆脱了 free(p) 行。但我仍然没有看到问题出在哪里。
  • @user2826609 编辑后实际上并没有删除任何节点,只要循环head-&gt;value == 0即可。如果head-&gt;value 不为零,那么您只需退出循环并返回列表的头部。
【解决方案2】:

你的函数应该通过 return head 或 Node **head 作为参数返回新的 head

head->如果你根本没有头,索引就会崩溃

Node * list_insert_update_remove(Node **head, int value, int index) 
{
  Node *node = List_create(...);
  if (*head == NULL) 
    *head = node;
  else {
    Node *prev = NULL;
    Node *list = head;
    while (list) {
      if (index < list->index) { //prepend
        if (prev == NULL) // before head
          *head = node; 
        else {
          prev->next = node; // into the middle/end
          node->next = list;
        }
        break;
      } else if (index == list->index) {
        //update or remove (execercise)
        break;
      } else if (list->next == NULL) { // append at end
        list->next = node;
        break;
      }
      prev = list;
      list = list->next;
    }
  }

  return *head;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多