class Node:
# Creating a node
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def searchNodes(self, x, y):
currentX = currentY = self.head
prevX = prevY = None
# search for x
while currentX and currentX.data != x:
prevX = currentX
currentX = currentX.next
# search for y
while currentY and currentY.data != y:
prevY = currentY
currentY = currentY.next
return prevX, currentX, prevY, currentY
def swap(self, x, y):
# both keys are same or null, do nothing
if x == y:
return
prevX, currentX, prevY, currentY = self.searchNodes(x, y)
if currentX is None or currentY is None:
return # x or y not found in the list
# x is not head
if prevX is not None:
prevX.next = currentY
else:
# make y as head
self.head = currentY
# y is not head
if prevY is not None:
prevY.next = currentX
else:
# make x as head
self.head = currentX
# swap remaining pointers
temp = currentX.next
currentX.next = currentY.next
currentY.next = temp
# Ensure the last node points to None
if currentX.next is None:
currentX.next = None
if currentY.next is None:
currentY.next = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def printLinkedList(self):
temp = self.head
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("Null") # To mark the end of the list
if __name__ == '__main__':
linked_list = LinkedList()
# Assign data values
linked_list.push(5)
linked_list.push(4)
linked_list.push(3)
linked_list.push(2)
linked_list.push(1)
# Print the linked list data
print('Before Swap: ')
linked_list.printLinkedList()
linked_list.swap(1, 3)
# Print the linked list data
print('\nAfter Swap: ')
linked_list.printLinkedList()