-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path100-singly_linked_list.py
More file actions
57 lines (45 loc) · 1.32 KB
/
Copy path100-singly_linked_list.py
File metadata and controls
57 lines (45 loc) · 1.32 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
#!/usr/bin/python3
class Node:
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")
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) and value is not None:
raise TypeError("next_node must be a Node object")
self.__next_node = value
class SinglyLinkedList:
def __str__(self):
rtn = ""
ptr = self.__head
while ptr is not None:
rtn += str(ptr.data)
if ptr.next_node is not None:
rtn += "\n"
ptr = ptr.next_node
return rtn
def __init__(self):
self.__head = None
def sorted_insert(self, value):
ptr = self.__head
while ptr is not None:
if ptr.data > value:
break
ptr_prev = ptr
ptr = ptr.next_node
newNode = Node(value, ptr)
if ptr == self.__head:
self.__head = newNode
else:
ptr_prev.next_node = newNode