Swap two adjacent elements by adjusting only the links ( and not the data ) using a .…
- User
Swap two adjacent elements by adjusting only the links ( and not the data ) using a . singly linked lists b . doubly linked lists
- Assistant
a. Singly Linked Lists:
To swap two adjacent elements in a singly linked list, we need to adjust the links of the nodes. Since singly linked lists only have a reference to their next node, we can't directly swap the nodes. However, we can swap the links between the nodes.
Here is an example code to swap two adjacent elements in a singly linked list:
class Node: def __init__(self, data): self.data = data self.next = None def swap_adjacent_elements(head): if head is None or head.next is None: return head # Initialize pointers prev = None curr = head # Swap links of adjacent nodes while curr and curr.next: next_node = curr.next curr.next = next_node.next next_node.next = curr if prev: prev.next = next_node else: head = next_node prev = curr curr = curr.next return headIn this code, we iterate through the list and swap the links of adjacent nodes. We also keep track of the previous node to correctly adjust the links. The head of the modified list is returned.
b. Doubly Linked Lists:
In a doubly linked list, each node has references to both its previous and next nodes. This makes it easier to swap adjacent elements. We can directly swap the nodes and adjust the links accordingly.
Here is an example code to swap two adjacent elements in a doubly linked list:
class Node: def __init__(self, data): self.data = data self.prev = None self.next = None def swap_adjacent_elements(head): if head is None or head.next is None: return head # Initialize pointers prev = None curr = head next_node = head.next # Swap nodes and adjust links curr.next = next_node.next if curr.next: curr.next.prev = curr next_node.next = curr curr.prev = next_node head = next_node # Recurse for the rest of the list curr.next = swap_adjacent_elements(curr.next) if curr.next: curr.next.prev = curr return headIn this code, we swap the nodes and adjust the links accordingly. We also recursively call the function for the rest of the list to swap all adjacent elements. The head of the modified list is returned.