Reverse a Doubly Linked List | Set 4 ( Swapping Data ) | Python3 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
import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def newNode ( val ) : NEW_LINE INDENT temp = Node ( val ) NEW_LINE temp . data = val NEW_LINE temp . prev = None NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT while ( head . next != None ) : NEW_LINE INDENT print ( head . data , end = " < - - > " ) NEW_LINE head = head . next NEW_LINE DEDENT print ( head . data ) NEW_LINE DEDENT def insert ( head , val ) : NEW_LINE INDENT temp = newNode ( val ) NEW_LINE temp . next = head NEW_LINE ( head ) . prev = temp NEW_LINE ( head ) = temp NEW_LINE return head NEW_LINE DEDENT def reverseList ( head ) : NEW_LINE INDENT left = head NEW_LINE right = head NEW_LINE while ( right . next != None ) : NEW_LINE INDENT right = right . next NEW_LINE DEDENT while ( left != right and left . prev != right ) : NEW_LINE INDENT t = left . data NEW_LINE left . data = right . data NEW_LINE right . data = t NEW_LINE left = left . next NEW_LINE right = right . prev NEW_LINE DEDENT return head NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = newNode ( 5 ) NEW_LINE head = insert ( head , 4 ) NEW_LINE head = insert ( head , 3 ) NEW_LINE head = insert ( head , 2 ) NEW_LINE head = insert ( head , 1 ) NEW_LINE printList ( head ) NEW_LINE print ( " List ▁ After ▁ Reversing " ) NEW_LINE head = reverseList ( head ) NEW_LINE printList ( head ) NEW_LINE DEDENT