• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

Linked list insertion at arbitrary point C

Joined
Jun 29, 2006
Messages
230 (0.04/day)
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;
};
 

W1zzard

Administrator
Staff member
Joined
May 14, 2004
Messages
27,050 (3.71/day)
Processor Ryzen 7 5700X
Memory 48 GB
Video Card(s) RTX 4080
Storage 2x HDD RAID 1, 3x M.2 NVMe
Display(s) 30" 2560x1600 + 19" 1280x1024
Software Windows 10 64-bit
http://en.wikipedia.org/wiki/Linked_list gives a pretty good overview and explains the insert operation nicely

 
Top