-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list.py
More file actions
65 lines (52 loc) · 1.81 KB
/
Copy pathlinked_list.py
File metadata and controls
65 lines (52 loc) · 1.81 KB
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
from node import Node
class LinkedList:
def __init__(self, value=None):
self.head_node = Node(value)
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 __str__(self):
curr = self.head_node
ret_string = str(curr.get_value())
while curr.get_next_node():
curr = curr.get_next_node()
ret_string += " -> {}".format(str(curr.get_value()))
return ret_string
def __len__(self):
count = 0
curr = self.head_node
while curr:
count += 1
curr = curr.get_next_node()
return count
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())
break
else:
current_node = next_node
ll = LinkedList(5)
ll.insert_beginning(11)
ll.insert_beginning(3)
print(ll)
print("Node Count: " + str(len(ll))) # Node Count: 3
ll2 = LinkedList()
print(ll2)
print("Node Count: " + str(len(ll2))) # Node Count: 0