Program to reverse a doubly linked list

In doubly linked list we are not restricted to move in one direction unlike in singly linked list because in doubly linked list we have two pointers in one node that is next pointer and previous pointer.so that we can move in both directions.Taking the advantage of this property of doubly linked list it is more easier to reverse doubly linked list as compared to singly linked list.The logic of the program is simple.We are going upto middle of doubly linked list and swap the first node and last node and so on until the linked list is reversed.

struct node
{
node *next;
node *previous;
int data;
}
void reverse(struct node *head)
{
node *firstnode;
node *secondnode;
int l;
int length=0;
struct node *tail=head;
while(tail!=NULL)
{
tail=tail->next;
length++;
}
firstnode=head;
secondnode=tail;
l=length/2;
node *temp;
for(int i=0;i<l;i++)
{
temp=firstnode->data;
firstnode->data=secondnode->data;
secondnode->data=temp;
firstnode=firstnode->next;
secondnode=secondnode->previous;
}
}

Comments

  1. How can you assign int type to node* type
    temp=firstnode->data;

    ReplyDelete

Post a Comment

Popular posts from this blog

Tricky Questions or Puzzles in C

Program to uncompress a string ie a2b3c4 to aabbbcccc

Programs and Puzzles in technical interviews i faced