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

Linked list insertion at arbitrary point C

Discussion in 'Programming & Webmastering' started by boogerlad, Mar 8, 2013.

  1. boogerlad

    Joined:
    Jun 29, 2006
    Messages:
    219 (0.07/day)
    Thanks Received:
    12
    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;
    };
     
  2. W1zzard

    W1zzard Administrator Staff Member

    Joined:
    May 14, 2004
    Messages:
    14,871 (3.93/day)
    Thanks Received:
    11,596

Currently Active Users Viewing This Thread: 1 (0 members and 1 guest)

Share This Page