Page 2 of 2 FirstFirst 12
Results 11 to 13 of 13

Thread: [C]Why do we need double pointers for inserting in a link list

  1. #11
    Join Date
    Jul 2007
    Location
    The Internet
    Beans
    Hidden!
    Distro
    Ubuntu

    Re: [C]Why do we need double pointers for inserting in a link list

    Instead do:


    Code:
    LLINK *t_last = NULL;
    
    while(t!=NULL)
    {
       t_last = t;
       t = t->next;
    }
    
    t_last->next = newnode;
    Last edited by Sporkman; September 16th, 2009 at 06:22 PM.

  2. #12
    Join Date
    Jul 2007
    Location
    The Internet
    Beans
    Hidden!
    Distro
    Ubuntu

    Re: [C]Why do we need double pointers for inserting in a link list

    ...or:

    Code:
    while(t->next!=NULL)
    {
       t = t->next;
    }
    
    t->next = newnode;
    Last edited by Sporkman; September 16th, 2009 at 06:24 PM.

  3. #13
    Join Date
    Jun 2007
    Location
    Maryland, US
    Beans
    6,288
    Distro
    Kubuntu

    Re: [C]Why do we need double pointers for inserting in a link list

    Maintaining a pointer to the tail of the linked list would undoubtedly be more efficient than iterating node by node, until the end of the list is found.

    Here's a basic example of using a tail pointer:
    Code:
    #include <stdlib.h>
    #include <assert.h>
    
    struct Node
    {
       int          num;
       struct Node* next;
    };
    
    struct List
    {
       struct Node* head;
       struct Node* tail;
    };
    
    void insert(struct List* list, int num)
    {
       assert(list != 0);
    
       struct Node* elem = malloc(sizeof(struct Node));
    
       elem->num  = num;
       elem->next = 0;
    
       if (list->head == 0)
       {
          list->head = elem;
          list->tail = list->head;
       }
       else
       {
          list->tail->next = elem;
          list->tail = elem;
       }
    }
    
    int main()
    {
       struct List list = {0, 0};
    
       insert(&list, 23);
       insert(&list, 11);
       insert(&list, 40);
    
       // ...
    
       return 0;
    }
    Last edited by dwhitney67; September 16th, 2009 at 06:40 PM.

Page 2 of 2 FirstFirst 12

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •