facebook like button

14 July, 2011

program 67: doubly linked list

The need:
      This program was written to learn how to use a doubly linked list. But the question come, "why is doubly linked list needed???" First of all I want to tell that the name doubly linked list comes from the fact that this linked is in deed connected doubly. Meaning is that each node has the address of its previous and next node unlike singly connected linked lists in which each node had address of its next node. So in singly connected linked lists we can traverse in only forward direction while in doubly connected inked list we can traverse in both directions. This is the need and plus point of doubly connected linked lists.




The code:
-----------------------------------------------------

// This a basic program to make a doublly linked list and to do some operation on it
#include<stdio.h.>
#include<stdlib.h>
// defining data-type node
struct linked_list
{
int num;
struct linked_list *next,*prev ;
} ;
typedef struct linked_list node ;
//declaration of functions
void create_list(node *p);
void sort(node *p);
void print(node *list);
void exchange(int *,int *);
main()
{
    int i;
    node *head ;
    head=(node *)malloc(sizeof(node));
    head->prev=NULL;
    printf("Enter a element numbers .\n");
    printf("Type -999 to end :\n");
    create_list(head);
    printf("The list created Successfully .\n");
    printf("The list is .\n");
    print(head);
    sort(head);
    printf("\nThe sorted list is .\n");
    print(head);
}
void create_list(node *list)
{
    scanf("%d",&list->num);
    if(list->num==-999)
        list->next=NULL;
    else
    {
        list->next=(node *)malloc(sizeof(node));
        list->next->prev=list;
        create_list(list->next);         //recursion
    }
}

void exchange(int *s1,int *s2)
{
    int temp;
    temp =*s1;
    *s1=*s2;
    *s2=temp;
}

void print(node *list)
{
    if(list->next!=NULL)
    {
    printf("%d-->",list->num);
    if(list->next->next==NULL)
        printf("END\n");
    print(list->next); //recursion
    }
}

void sort(node *list)
{
    node *p,*q;
    for(p=list;(p->next)!=NULL;p=p->next)
    for(q=list;(q->next->next)!=NULL;q=q->next)
    {
    if(q->num > q->next->num)
        exchange(&(q->num),&(q->next->num));
    }
}

-----------------------------------------------------
The approach:
    The approach is same as singly linked list. See there is a slight change in the structure of the datatype node and to keep track of *prev there are slight changes made in the UDFs also.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply