-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_middle.py
87 lines (63 loc) · 2.11 KB
/
find_middle.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next_node(self):
return self.next_node
def set_next_node(self, next_node):
self.next_node = next_node
class LinkedList:
def __init__(self, value=None):
if value is not None:
self.head_node = Node(value)
else:
self.head_node = None
def get_head_node(self):
return self.head_node
def insert_beginning(self, new_value):
new_node = Node(new_value)
new_node.set_next_node(self.head_node)
self.head_node = new_node
def stringify_list(self):
string_list = ""
current_node = self.get_head_node()
while current_node:
if current_node.get_value() is not None:
string_list += str(current_node.get_value()) + "\n"
current_node = current_node.get_next_node()
return string_list
def remove_node(self, value_to_remove):
current_node = self.get_head_node()
if current_node.get_value() == value_to_remove:
self.head_node = current_node.get_next_node()
else:
while current_node:
next_node = current_node.get_next_node()
if next_node.get_value() == value_to_remove:
current_node.set_next_node(next_node.get_next_node())
current_node = None
else:
current_node = next_node
######################################################################
# Complete this function:
def find_middle(linked_list):
slow = linked_list.head_node
fast = linked_list.head_node
while fast and fast.get_next_node():
slow = slow.get_next_node()
fast = fast.get_next_node().get_next_node()
return slow
######################################################################
# Driver Code
def generate_test_linked_list(length):
linked_list = LinkedList()
for i in range(length, 0, -1):
linked_list.insert_beginning(i)
return linked_list
# Use this to test your code:
test_list = generate_test_linked_list(7)
print(test_list.stringify_list())
middle_node = find_middle(test_list)
print(middle_node.value)