Skip to content

Commit 5e53367

Browse files
partitioning a linked list
1 parent 8523aac commit 5e53367

File tree

1 file changed

+91
-0
lines changed
  • Python/chapter02/2.4 - Partition

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
#!/usr/bin/python3
2+
3+
import unittest
4+
5+
6+
class Node:
7+
def __init__(self, data, next=None):
8+
self.data = data
9+
self.next = next
10+
11+
def __str__(self):
12+
return str(self.data)
13+
14+
15+
class SinglyLinkedList:
16+
def __init__(self):
17+
self.head = None
18+
19+
def addNode(self, data):
20+
node = Node(data)
21+
if self.head is None:
22+
self.head = node
23+
else:
24+
temp = self.head
25+
while temp.next:
26+
temp = temp.next
27+
temp.next = node
28+
print('Node added to LL--->', data)
29+
30+
def printList(self):
31+
if self.head is None:
32+
print('No LinkedList to print')
33+
return
34+
35+
temp = self.head
36+
while temp:
37+
print(temp.data)
38+
temp = temp.next
39+
40+
def partition(self, part):
41+
'''However, in a linked list, the situation is much easier. Rather than shifting and swapping elements, we can actually create two different linked lists: one for elements less than x, and one for elements greater than or equal to x.'''
42+
if self.head is None:
43+
print('No LinkedList to print')
44+
return
45+
46+
temp = self.head
47+
before = SinglyLinkedList()
48+
after = SinglyLinkedList()
49+
while temp.next:
50+
if temp.data >= part:
51+
after.addNode(temp.data)
52+
else:
53+
before.addNode(temp.data)
54+
temp = temp.next
55+
56+
# combine the two linked lists
57+
self.head = before.head
58+
temp = before.head
59+
while temp.next:
60+
temp = temp.next
61+
temp.next = after.head
62+
63+
64+
class Test(unittest.TestCase):
65+
66+
@classmethod
67+
def setUpClass(cls):
68+
cls.l = SinglyLinkedList()
69+
cls.l.printList()
70+
cls.l.addNode(3)
71+
cls.l.addNode(20)
72+
cls.l.addNode(21)
73+
cls.l.addNode(5)
74+
cls.l.addNode(8)
75+
cls.l.addNode(5)
76+
cls.l.addNode(10)
77+
cls.l.addNode(2)
78+
cls.l.addNode(1)
79+
cls.l.printList()
80+
81+
@classmethod
82+
def tearDownClass(cls):
83+
pass
84+
85+
def test1(self):
86+
self.l.partition(5)
87+
self.l.printList()
88+
89+
90+
if __name__ == '__main__':
91+
unittest.main()

0 commit comments

Comments
 (0)