【发布时间】:2013-10-31 18:39:34
【问题描述】:
我得到一个名为“head”的稀疏数组,它是具有索引和值的二维数组。所以像: (3, 100) (6,200) (8,100)
- 我必须按升序将一个节点(值、索引)插入到这个稀疏数组中。因此,如果给我 (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