Code:
void sequence_insert_at(Sequence s, int pos, int item)
{
if(pos)
{
struct node* ptr = s->lst;
for(; pos > 1; --pos)
{
ptr = ptr->rest;
}
add_to_front(&ptr->rest, item);
}
else
{
add_to_front(&s->lst, item);
}
++s->length;
}
This code works fine, but I'm wondering why
Code:
void sequence_insert_at(Sequence s, int pos, int item)
{
if(pos)
{
struct node* ptr = s->lst;
for(; pos > 0; --pos)
{
ptr = ptr->rest;
}
add_to_front(&ptr, item);
}
else
{
add_to_front(&s->lst, item);
}
++s->length;
}
doesn't seem to work. In fact, all it does is do nothing when insertion does not happen in the beginning. I don't see why it wouldn't work, since this is just going one iteration deeper. This means that some pointer is not getting saved/isn't pointing in the right direction, but why? My instructor drew me this diagram, but he seemed rather annoyed so I didn't ask him more questions.
Code:
a->b->c->d
insert e 1
e
|
V
a->b->c->d
He said " you're not inserting e between a & b... you're just pointing e to b"
Here is some relevant code that is constant.
Code:
void add_to_front(struct node **ptrhead, int item) {
assert(ptrhead != NULL); // ptrhead must be valid
struct node *newnode = malloc(sizeof(struct node));
if (newnode == NULL) {
printf("ERROR! add_to_front ran out of memory!\n");
exit(EXIT_FAILURE);
}
newnode->first = item;
newnode->rest = *ptrhead;
*ptrhead = newnode;
}
struct node {
int first;
struct node *rest;
};
typedef struct sequence *Sequence;
struct sequence
{
struct node* lst;
int length;
};