Thread: Changing single to double linked list

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    12

    Changing single to double linked list

    i did a search but couldn't really find an exact answer. i need to create a double linked list for my program, which i've only done single before. i know you have to put a previous pointer but i forgot that i should probably make it point back to the previous structure (yeah i know i'm dumb) but i really don't know how to do that. i attempted putting

    current->next->prev=current

    right after i allocated space for the next structure. but that didn't work. it was all i could think of. probably doesn't even make sense. i'd appreciate any help. thank you

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Double linked lists are FAR simpler than single linked lists. Trust me on this one. They make it way easier to delete nodes from. Given a single node, you can delete that node. You don't have to traverse the entire list to do it. Simply cut it free.

    That being said...
    Code:
    struct node* newnode( ...args... )
    {
        struct node *newnode;
        newnode = malloc( sizeof( struct node ) );
        newnode->prev = NULL; /*1*/
        newnode->next = someNode; /*2*/
        someNode->next = newnode; /*3*/
        someNode->prev = newnode; /*3*/
        newnode->something = somearg;
        return newnode;
    }
    1 - Point this to NULL if you are prepending to a list. Point this to 'someNode' if you are appending.

    2 - Point this to NULL if you are appending to a list. Point this to 'someNode' if you are prepending.

    3 - Use one or the other, depending if you are prepending or appending.

    If you are inserting, it is slightly different, except instead of using nulls, you use 'someNode->prev', 'someNode->next', 'someNode->prev->next' and 'someNode->next->prev', depending on if you are inserting after or before 'someNode'.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help! Placement of nodes in a Linked List
    By lostmyshadow in forum C Programming
    Replies: 6
    Last Post: 12-17-2007, 01:21 PM
  2. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 10:01 AM
  3. Linked list with two class types within template.
    By SilasP in forum C++ Programming
    Replies: 3
    Last Post: 02-09-2002, 06:13 AM
  4. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM