Reverse a Doubly Linked List | Set 4 ( Swapping Data ) | Cpp Program to Reverse a List using Data Swapping ; Insert a new node at the head of the list ; Function to reverse the list ; Traverse the list and set right pointer to end of list ; Swap data of left and right pointer and move them towards each other until they meet or cross each other ; Swap data of left and right pointer ; Advance left pointer ; Advance right pointer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * prev , * next ; } ; Node * newNode ( int val ) { Node * temp = new Node ; temp -> data = val ; temp -> prev = temp -> next = nullptr ; return temp ; } void printList ( Node * head ) { while ( head -> next != nullptr ) { cout << head -> data << " ▁ < - - > ▁ " ; head = head -> next ; } cout << head -> data << endl ; } void insert ( Node * * head , int val ) { Node * temp = newNode ( val ) ; temp -> next = * head ; ( * head ) -> prev = temp ; ( * head ) = temp ; } void reverseList ( Node * * head ) { Node * left = * head , * right = * head ; while ( right -> next != nullptr ) right = right -> next ; while ( left != right && left -> prev != right ) { swap ( left -> data , right -> data ) ; left = left -> next ; right = right -> prev ; } } int main ( ) { Node * head = newNode ( 5 ) ; insert ( & head , 4 ) ; insert ( & head , 3 ) ; insert ( & head , 2 ) ; insert ( & head , 1 ) ; printList ( head ) ; cout << " List ▁ After ▁ Reversing " << endl ; reverseList ( & head ) ; printList ( head ) ; return 0 ; }