I am given a sparse-array called "head", which is two-dimensional having an index, and a value. So something like : (3, 100) (6,200) (8,100)
- I have to insert a node (value, index) into this sparse array in ascending order. So if I am given (2,100), the list should look like: (2, 100) (3,100) (6,200) (8,100)
Similarly if I am given (4,200), it should return (3,100) (4,200) (6,200) (8,100)
Condition 1: if the indices are same, then I must add the values
So if I am given (3,100), then I should return (3,200) (6,200) (8,100)
Condition 2: if the indices are same, and the value is zero, then the value should be removed. So if the array is (3,-100), I must return
(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;
}
My understanding is that when I make head->next the new head, that should get rid of the original entry.
But the 0 value-ed index continues to remain in the list. Result is (3,0) (6,200) (8,100)
If someone can help me with figuring out what I'm doing wrong (and perhaps even why) I would really appreciate it.