Reverse a Doubly Linked List | Set 4 ( Swapping Data ) | javascript 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
class Node { constructor ( val ) { this . data = val ; this . prev = null ; this . next = null ; } } function newNode ( val ) { var temp = new Node ( ) ; temp . data = val ; temp . prev = temp . next = null ; return temp ; } function printList ( head ) { while ( head . next != null ) { document . write ( head . data + " " ) ; head = head . next ; } document . write ( head . data ) ; } function insert ( head , val ) { var temp = newNode ( val ) ; temp . next = head ; ( head ) . prev = temp ; ( head ) = temp ; return head ; } function reverseList ( head ) { var left = head , right = head ; while ( right . next != null ) right = right . next ; while ( left != right && left . prev != right ) { var t = left . data ; left . data = right . data ; right . data = t ; left = left . next ; right = right . prev ; } return head ; } var head = newNode ( 5 ) ; head = insert ( head , 4 ) ; head = insert ( head , 3 ) ; head = insert ( head , 2 ) ; head = insert ( head , 1 ) ; printList ( head ) ; document . write ( " " ) ; head = reverseList ( head ) ; printList ( head ) ;