> doubly linked list program in c ~ Online tutorial

doubly linked list program in c

doubly linked list program in c

        This a sample program of double linked list! the advantage of double over single is that singly linked list has the node inserted only at one end. and the pointer corresponds to the next pointer. but in a doubly linked list, the node pointer points to the both previous and the next node. singly linked list has two nodes doubly linked list has three nodes A doubly linked list makes sense when you need to traverse the list in both directions. You aren't able to do that with a singly linked list.



Sample Code

    #include <stdio.h>
    #include <stdlib.h>
    
    struct dllist
{
     int number;
     struct dllist *next;
     struct dllist *prev;
    };
    
    struct dllist *head, *tail;
    
    void append_node(struct dllist *lnode);
    void insert_node(struct dllist *lnode, struct dllist *after);
    void remove_node(struct dllist *lnode);
    
    int main(void) {
     struct dllist *lnode;
     int i = 0;
    
     /* add some numbers to the double linked list */
     for(i = 0; i <= 5; i++) {
      lnode = (struct dllist *)malloc(sizeof(struct dllist));
      lnode->number = i;
      append_node(lnode);
     }
    
     /* print the dll list */
     for(lnode = head; lnode != NULL; lnode = lnode->next) {
      printf("%dn", lnode->number);
     }
    
     /* destroy the dll list */
     while(head != NULL)
      remove_node(head);
    
     return 0;
    }
    
    void append_node(struct dllist *lnode)
{
     if(head == NULL)
 {
      head = lnode;
      lnode->prev = NULL;
     }
else
{
      tail->next = lnode;
      lnode->prev = tail;
     }
    
     tail = lnode;
     lnode->next = NULL;
    }
    
    void insert_node(struct dllist *lnode, struct dllist *after)
{
     lnode->next = after->next;
     lnode->prev = after;
    
     if(after->next != NULL)
      after->next->prev = lnode;
     else
      tail = lnode;
    
     after->next = lnode;
    }
    
    void remove_node(struct dllist *lnode)
{
     if(lnode->prev == NULL)
      head = lnode->next;
     else
      lnode->prev->next = lnode->next;
    
     if(lnode->next == NULL)
      tail = lnode->prev;
     else
      lnode->next->prev = lnode->prev;
    }


    

Please Give Us Your 1 Minute In Sharing This Post!
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Powered By: BloggerYard.Com

0 comments: