-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path100-singly_linked_list.py
More file actions
executable file
·67 lines (58 loc) · 1.86 KB
/
Copy path100-singly_linked_list.py
File metadata and controls
executable file
·67 lines (58 loc) · 1.86 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
66
67
#!/usr/bin/python3
class Node:
"""Node of a singly linked list"""
def __init__(self, data, next_node=None):
self.__data = data
self.__next_node = next_node
@property
def data(self):
return self.__data
@data.setter
def data(self, value):
if (not isinstance(value, int)):
raise TypeError("data must be an integer")
else:
self.__data = value
@property
def next_node(self):
return self.__next_node
@next_node.setter
def next_node(self, value):
if (not isinstance(value, Node) or value is not None):
raise TypeError("next_node must be a Node Object")
else:
self.__next_node = value
class SinglyLinkedList:
"""Represent a singly-linked list."""
def __init__(self):
"""Initalize a new SinglyLinkedList."""
self.__head = None
def sorted_insert(self, value):
"""Insert a new Node to the SinglyLinkedList.
The node is inserted into the list at the correct
ordered numerical position.
Args:
value (Node): The new Node to insert.
"""
new = Node(value)
if self.__head is None:
new.next_node = None
self.__head = new
elif self.__head.data > value:
new.next_node = self.__head
self.__head = new
else:
tmp = self.__head
while (tmp.next_node is not None and
tmp.next_node.data < value):
tmp = tmp.next_node
new.next_node = tmp.next_node
tmp.next_node = new
def __str__(self):
"""Implementing how print(SinglyLinkedList)."""
values = []
tmp = self.__head
while tmp is not None:
values.append(str(tmp.data))
tmp = tmp.next_node
return ('\n'.join(values))