mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-18 16:27:02 +00:00
enhance swapping code in link (#1660)
* enhance swapping code in link * heapify do not recursive * fix * fix identifier and add test * typing.Any and LinkedList instead of Linkedlist * typing.Any and LinkedList instead of Linkedlist
This commit is contained in:
parent
b492e64417
commit
56e7ae01d2
|
@ -1,72 +1,55 @@
|
|||
from typing import Any
|
||||
|
||||
|
||||
class Node:
|
||||
def __init__(self, data):
|
||||
def __init__(self, data: Any):
|
||||
self.data = data
|
||||
self.next = None
|
||||
|
||||
|
||||
class Linkedlist:
|
||||
class LinkedList:
|
||||
def __init__(self):
|
||||
self.head = None
|
||||
|
||||
def print_list(self):
|
||||
temp = self.head
|
||||
while temp is not None:
|
||||
print(temp.data)
|
||||
print(temp.data, end=' ')
|
||||
temp = temp.next
|
||||
print()
|
||||
|
||||
# adding nodes
|
||||
def push(self, new_data):
|
||||
def push(self, new_data: Any):
|
||||
new_node = Node(new_data)
|
||||
new_node.next = self.head
|
||||
self.head = new_node
|
||||
|
||||
# swapping nodes
|
||||
def swapNodes(self, d1, d2):
|
||||
prevD1 = None
|
||||
prevD2 = None
|
||||
if d1 == d2:
|
||||
def swap_nodes(self, node_data_1, node_data_2):
|
||||
if node_data_1 == node_data_2:
|
||||
return
|
||||
else:
|
||||
# find d1
|
||||
D1 = self.head
|
||||
while D1 is not None and D1.data != d1:
|
||||
prevD1 = D1
|
||||
D1 = D1.next
|
||||
# find d2
|
||||
D2 = self.head
|
||||
while D2 is not None and D2.data != d2:
|
||||
prevD2 = D2
|
||||
D2 = D2.next
|
||||
if D1 is None and D2 is None:
|
||||
node_1 = self.head
|
||||
while node_1 is not None and node_1.data != node_data_1:
|
||||
node_1 = node_1.next
|
||||
|
||||
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
|
||||
# if D1 is head
|
||||
if prevD1 is not None:
|
||||
prevD1.next = D2
|
||||
else:
|
||||
self.head = D2
|
||||
# if D2 is head
|
||||
if prevD2 is not None:
|
||||
prevD2.next = D1
|
||||
else:
|
||||
self.head = D1
|
||||
temp = D1.next
|
||||
D1.next = D2.next
|
||||
D2.next = temp
|
||||
|
||||
|
||||
# swapping code ends here
|
||||
node_1.data, node_2.data = node_2.data, node_1.data
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
list = Linkedlist()
|
||||
list.push(5)
|
||||
list.push(4)
|
||||
list.push(3)
|
||||
list.push(2)
|
||||
list.push(1)
|
||||
ll = LinkedList()
|
||||
for i in range(5, 0, -1):
|
||||
ll.push(i)
|
||||
|
||||
list.print_list()
|
||||
ll.print_list()
|
||||
|
||||
list.swapNodes(1, 4)
|
||||
ll.swap_nodes(1, 4)
|
||||
print("After swapping")
|
||||
list.print_list()
|
||||
ll.print_list()
|
||||
|
|
Loading…
Reference in New Issue
Block a user