Friday, February 6, 2015

reverse the DLL iteratively and recursively.

Write a C function to reverse a given Doubly Linked List
See below diagrams for example.
     (a) Original Doubly Linked List  

     (b) Reversed Doubly Linked List  







//Assume that the head and tail pointers are made global , and so is available to the function.

// Iteratively...


void reverseListIteratively()
{
struct node *temp,*p=NULL;
p=head;
while(1)
{
temp=p->left;
p->left=p->right;
p->right=temp;

if((p->right)==NULL)
{
tail=p;
}
if((p->left)==NULL)
{
head=p;
}

p=p->left;
if(p==NULL)
{
break;
}
}



}



// recursively....


void reverseListRecursively(struct node *p)
{
struct node *temp=NULL;

if(p==NULL)
return;

temp=p->left;
p->left=p->right;
p->right=temp;

if((p->right)==NULL)
{
tail=p;
}
if((p->left)==NULL)
{
head=p;
}

reverseListRecursively(p->left);


}



No comments:

Post a Comment