I wrote reverse logic but it is not giving desired output.Actually when I printed only linked list Traversal function then it prints finely all elements but when I called reverse function and after calling traversal function then it is not giving reverse linked list. I am not getting where i am wrong.Please resolve my issue. Thanks in advance!!
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
struct Node *prev;
};
void linkedListTransversal(struct Node *ptr)
{
while (ptr != NULL)//&& ptr->prev != NULL
{
printf("Element:%d\n", ptr->data);
ptr = ptr->next;
}
}
void linkedListRevTransversal(struct Node *head)
{
struct Node * temp=NULL;
struct Node * p=head;
while (p != NULL)
{
temp=p->prev;
p->prev=p->next;
p->next=temp;
p=p->prev;
}
if(temp != NULL )
head = temp->prev;
}
int main()
{
struct Node *head;
struct Node *second;
struct Node *third;
struct Node *fourth;
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
fourth = (struct Node *)malloc(sizeof(struct Node));
head->data = 10;
head->prev=NULL;
head->next = second;
second->data = 20;
head->prev=head;
second->next = third;
third->data = 30;
head->prev=third;
third->next = fourth;
fourth->data = 40;
head->prev=fourth;
fourth->next = NULL;
linkedListTransversal(head);
linkedListRevTransversal(head);
linkedListTransversal(head);
}
Output:
Element:10
Element:20
Element:30
Element:40
Element:10
Element:40