Question: Write a function to reverse a doubly linked list. The function should take in the head node of the list and return the new head node of the reversed list. The nodes of the doubly linked list have the following properties:
value attribute, which stores an integer value.prev attribute, which points to the previous node in the list.next attribute, which points to the next node in the list.
You need to implement the reverse_doubly_linked_list function.class Node:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
def reverse_doubly_linked_list(head):
# Implement this function
# Example usage:
# Input: 1 <-> 2 <-> 3 <-> 4 <-> 5
# Output: 5 <-> 4 <-> 3 <-> 2 <-> 1
Answer:
To reverse a doubly linked list, we need to change the direction of the next and prev pointers for each node. The following steps can be followed to reverse the list:
If the given head is None or the list is empty (i.e., head is None), return None as the reversed list.
Initialize three pointers: current pointing to the current node being processed, previous pointing to the previous node, and next pointing to the next node.
Iterate through the list starting from the head and update the prev and next pointers of each node accordingly until the current node becomes None.
In each iteration, store the next node current.next in the next pointer.
Set current.prev to next and current.next to previous.
Move the pointers ahead using previous = current and current = next. Repeat steps 4-6 until all nodes are reversed.
Finally, assign the next pointer of the last processed node to None and return the current previous node as the new head node of the reversed list.
Here is the implementation of the reverse_doubly_linked_list function in Python:
def reverse_doubly_linked_list(head):
if head is None:
return None
current = head
previous = None
while current is not None:
next_node = current.next
current.prev = next_node
current.next = previous
previous = current
current = next_node
head = previous
head.prev = None
return head
The time complexity of this solution is O(n) since it iterates through the list once, where n is the number of nodes in the list.