如何按升序创建链接列表

时间:2013-10-22 18:27:49

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

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

  1. 我必须按升序将一个节点(值,索引)插入到这个稀疏数组中。因此,如果给出(2,100),列表应如下所示: (2,100)(3,100)(6,200)(8,100)
  2. 同样,如果给予(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;
    
    }
    

    我的理解是,当我开头 - >接下来的新头时,应该摆脱原来的条目。

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

    如果有人能帮助我弄清楚我做错了什么(甚至可能是为什么),我会非常感激。

2 个答案:

答案 0 :(得分:2)

您的代码中存在未定义的行为。

当你这样做时

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

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

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

答案 1 :(得分:1)

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

返回新头

head-&gt;索引是一个崩溃,如果你根本没有头

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;
}
相关问题