Monday, 18 February 2013

Now its time to move on to doubly linked list.It has two pointers in every node-one points to the next node and the other points to the previous node.
Simple code to insert and display elements in a doubly linked list-

#include<stdio.h>
#include<stdlib.h>

struct node
{
int data;
struct node *prev;
struct node *next;
};

void append(struct node **,int);
void display(struct node *);
int main()
{
struct node *start=NULL;
append(&start,10);
append(&start,25);
append(&start,5);
append(&start,16);
append(&start,22);
append(&start,24);
append(&start,8);
append(&start,31);
append(&start,12);
printf("Original list\n");
display(start);
return 0;
}

void append(struct node **ps,int x)
{
struct node *temp,*temp2;
temp2=(struct node *)malloc(sizeof(struct node));
temp2->data=x;
temp2->next=NULL;
if(*ps==NULL)
{
*ps=temp2;
temp2->prev=NULL;
return;
}
temp=*ps;
while(temp->next!=NULL)
temp=temp->next;
temp->next=temp2;
temp2->prev=temp;
}

void display(struct node *p)
{
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->next;
}
}

No comments:

Post a Comment