-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoubly_linked_list_kth_last_node.py
66 lines (47 loc) · 1.57 KB
/
doubly_linked_list_kth_last_node.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import unittest
"""
Write a function kth_to_last_node() that takes an integer kk and the head_node of a linked list, and returns the
kth to last node in the list.
time complexity: n + k
space complexity: 1
"""
class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def kth_to_last_node(k, base_node):
current_node = base_node
while True:
if current_node.next:
current_node.next.prev = current_node
current_node = current_node.next
else:
break
for i in range(k - 1):
if current_node.prev:
current_node = current_node.prev
else:
return
return current_node
class Test(unittest.TestCase):
def setUp(self):
self.a = LinkedListNode("Angel Food")
self.b = LinkedListNode("Bundt")
self.c = LinkedListNode("Cheese")
self.d = LinkedListNode("Devil's Food")
self.e = LinkedListNode("Eccles")
self.a.next = self.b
self.b.next = self.c
self.c.next = self.d
self.d.next = self.e
def test_base_case(self):
# Returns the node with value "Devil's Food" (the 2nd to last node)
assert kth_to_last_node(2, self.a).value == "Devil's Food"
def test_1_case(self):
assert kth_to_last_node(1, self.a).value == "Eccles"
def test_5_case(self):
assert kth_to_last_node(5, self.a).value == "Angel Food"
def test_n_plus_1_case(self):
assert kth_to_last_node(10, self.a) is None
unittest.main(verbosity=2)