Skip to content

Commit 56e7ae0

Browse files
lanzhiwangonlinejudge95
authored andcommitted
enhance swapping code in link (TheAlgorithms#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
1 parent b492e64 commit 56e7ae0

File tree

1 file changed

+26
-43
lines changed

1 file changed

+26
-43
lines changed
+26-43
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,55 @@
1+
from typing import Any
2+
3+
14
class Node:
2-
def __init__(self, data):
5+
def __init__(self, data: Any):
36
self.data = data
47
self.next = None
58

69

7-
class Linkedlist:
10+
class LinkedList:
811
def __init__(self):
912
self.head = None
1013

1114
def print_list(self):
1215
temp = self.head
1316
while temp is not None:
14-
print(temp.data)
17+
print(temp.data, end=' ')
1518
temp = temp.next
19+
print()
1620

1721
# adding nodes
18-
def push(self, new_data):
22+
def push(self, new_data: Any):
1923
new_node = Node(new_data)
2024
new_node.next = self.head
2125
self.head = new_node
2226

2327
# swapping nodes
24-
def swapNodes(self, d1, d2):
25-
prevD1 = None
26-
prevD2 = None
27-
if d1 == d2:
28+
def swap_nodes(self, node_data_1, node_data_2):
29+
if node_data_1 == node_data_2:
2830
return
2931
else:
30-
# find d1
31-
D1 = self.head
32-
while D1 is not None and D1.data != d1:
33-
prevD1 = D1
34-
D1 = D1.next
35-
# find d2
36-
D2 = self.head
37-
while D2 is not None and D2.data != d2:
38-
prevD2 = D2
39-
D2 = D2.next
40-
if D1 is None and D2 is None:
41-
return
42-
# if D1 is head
43-
if prevD1 is not None:
44-
prevD1.next = D2
45-
else:
46-
self.head = D2
47-
# if D2 is head
48-
if prevD2 is not None:
49-
prevD2.next = D1
50-
else:
51-
self.head = D1
52-
temp = D1.next
53-
D1.next = D2.next
54-
D2.next = temp
32+
node_1 = self.head
33+
while node_1 is not None and node_1.data != node_data_1:
34+
node_1 = node_1.next
5535

36+
node_2 = self.head
37+
while node_2 is not None and node_2.data != node_data_2:
38+
node_2 = node_2.next
39+
40+
if node_1 is None or node_2 is None:
41+
return
5642

57-
# swapping code ends here
43+
node_1.data, node_2.data = node_2.data, node_1.data
5844

5945

6046
if __name__ == "__main__":
61-
list = Linkedlist()
62-
list.push(5)
63-
list.push(4)
64-
list.push(3)
65-
list.push(2)
66-
list.push(1)
47+
ll = LinkedList()
48+
for i in range(5, 0, -1):
49+
ll.push(i)
6750

68-
list.print_list()
51+
ll.print_list()
6952

70-
list.swapNodes(1, 4)
53+
ll.swap_nodes(1, 4)
7154
print("After swapping")
72-
list.print_list()
55+
ll.print_list()

0 commit comments

Comments
 (0)