2020-01-14 09:02:15 +00:00
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
|
2018-12-25 13:09:36 +00:00
|
|
|
class Node:
|
2020-01-14 09:02:15 +00:00
|
|
|
def __init__(self, data: Any):
|
2019-10-05 05:14:13 +00:00
|
|
|
self.data = data
|
2018-12-25 13:09:36 +00:00
|
|
|
self.next = None
|
|
|
|
|
|
|
|
|
2020-01-14 09:02:15 +00:00
|
|
|
class LinkedList:
|
2018-12-25 13:09:36 +00:00
|
|
|
def __init__(self):
|
|
|
|
self.head = None
|
|
|
|
|
|
|
|
def print_list(self):
|
|
|
|
temp = self.head
|
|
|
|
while temp is not None:
|
2020-01-18 12:24:33 +00:00
|
|
|
print(temp.data, end=" ")
|
2018-12-25 13:09:36 +00:00
|
|
|
temp = temp.next
|
2020-01-14 09:02:15 +00:00
|
|
|
print()
|
2018-12-25 13:09:36 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
# adding nodes
|
2020-01-14 09:02:15 +00:00
|
|
|
def push(self, new_data: Any):
|
2018-12-25 13:09:36 +00:00
|
|
|
new_node = Node(new_data)
|
|
|
|
new_node.next = self.head
|
|
|
|
self.head = new_node
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
# swapping nodes
|
2020-01-14 09:02:15 +00:00
|
|
|
def swap_nodes(self, node_data_1, node_data_2):
|
|
|
|
if node_data_1 == node_data_2:
|
2018-12-25 13:09:36 +00:00
|
|
|
return
|
|
|
|
else:
|
2020-01-14 09:02:15 +00:00
|
|
|
node_1 = self.head
|
|
|
|
while node_1 is not None and node_1.data != node_data_1:
|
|
|
|
node_1 = node_1.next
|
2018-12-25 13:09:36 +00:00
|
|
|
|
2020-01-14 09:02:15 +00:00
|
|
|
node_2 = self.head
|
|
|
|
while node_2 is not None and node_2.data != node_data_2:
|
|
|
|
node_2 = node_2.next
|
|
|
|
|
|
|
|
if node_1 is None or node_2 is None:
|
|
|
|
return
|
2018-12-25 13:09:36 +00:00
|
|
|
|
2020-01-14 09:02:15 +00:00
|
|
|
node_1.data, node_2.data = node_2.data, node_1.data
|
2018-12-25 13:09:36 +00:00
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2020-01-14 09:02:15 +00:00
|
|
|
ll = LinkedList()
|
|
|
|
for i in range(5, 0, -1):
|
|
|
|
ll.push(i)
|
2018-12-25 13:09:36 +00:00
|
|
|
|
2020-01-14 09:02:15 +00:00
|
|
|
ll.print_list()
|
2018-12-25 13:09:36 +00:00
|
|
|
|
2020-01-14 09:02:15 +00:00
|
|
|
ll.swap_nodes(1, 4)
|
2018-12-25 13:09:36 +00:00
|
|
|
print("After swapping")
|
2020-01-14 09:02:15 +00:00
|
|
|
ll.print_list()
|