Skip to content

Commit bf4ebc4

Browse files
return kth to last element in a singly linked list
1 parent 7f1881b commit bf4ebc4

File tree

1 file changed

+105
-0
lines changed
  • Python/chapter02/2.2 - Return Kth to Last

1 file changed

+105
-0
lines changed
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
#!/usr/bin/python3
2+
'''
3+
Return Kth to Last: Implement an algorithm to
4+
find the kth to last element of a singly linked list.
5+
'''
6+
import unittest
7+
8+
9+
class Node:
10+
def __init__(self, data, next=None):
11+
self.data = data
12+
self.next = next
13+
14+
def __str__(self):
15+
return str(self.data)
16+
17+
18+
class SinglyLinkedList:
19+
20+
def __init__(self):
21+
self.head = None
22+
self.size = 0
23+
24+
def insertHead(self, data):
25+
print('Inserting head!----->', data)
26+
n = Node(data)
27+
temp = self.head
28+
self.head = n
29+
self.head.next = temp
30+
31+
def addNode(self, data):
32+
if not self.head:
33+
n = Node(data)
34+
print('New Head added ---->', data)
35+
self.head = n
36+
else:
37+
n = self.head
38+
while (n.next):
39+
n = n.next
40+
41+
print('New Node added ---->', data)
42+
new_node = Node(data)
43+
n.next = new_node
44+
45+
def kthToLastElement(self, num):
46+
if num < 1:
47+
print('Must be a positive number')
48+
return
49+
50+
length = 0
51+
temp = self.head
52+
while temp:
53+
length += 1
54+
temp = temp.next
55+
56+
if num > length:
57+
print('Input number cannot be larger than number of nodes')
58+
else:
59+
temp = self.head
60+
for x in range(length - num):
61+
temp = temp.next
62+
63+
print("{}th to last element --->".format(num), temp.data)
64+
65+
def printList(self):
66+
n = self.head
67+
68+
print('Printing Singly Linked List')
69+
while(n):
70+
print(n)
71+
n = n.next
72+
73+
74+
class Test(unittest.TestCase):
75+
@classmethod
76+
def setUpClass(cls):
77+
cls.link = SinglyLinkedList()
78+
cls.link.addNode(-1)
79+
cls.link.addNode(-1)
80+
cls.link.addNode(4)
81+
cls.link.addNode(3)
82+
cls.link.addNode(4)
83+
cls.link.addNode(1)
84+
cls.link.addNode(20)
85+
cls.link.addNode(4)
86+
cls.link.addNode(4)
87+
88+
@classmethod
89+
def tearDownClass(cls):
90+
print('---Teardown successful---')
91+
92+
def test1(self):
93+
self.link.printList()
94+
95+
def test2(self):
96+
self.link.kthToLastElement(0)
97+
self.link.kthToLastElement(1)
98+
self.link.kthToLastElement(2)
99+
self.link.kthToLastElement(3)
100+
self.link.kthToLastElement(9)
101+
self.link.kthToLastElement(10)
102+
103+
104+
if __name__ == "__main__":
105+
unittest.main()

0 commit comments

Comments
 (0)