-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsorted_linked_list.py
66 lines (51 loc) · 1.3 KB
/
sorted_linked_list.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
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):
def __init__(self):
self.list = None
def insert(self, data):
node = Node(data)
# First node
if not self.list:
self.list = node
else:
curr = self.list
prev = None
# Move ahead
while curr:
if data < curr.data:
prev = curr
curr = curr.next
else:
break
# if not curr:
# curr = node
# prev.next = curr
# If two elements or swap second with first
if not prev:
node.next = self.list
self.list = node
else:
# General case
node.next = curr
prev.next = node
prev = node
def __repr__(self):
curr = self.list
queue = []
while curr:
queue.append(curr.data)
curr = curr.next
return str(queue)
def __len__(self):
return self.count
list = LinkedList()
list.insert(10)
list.insert(4)
list.insert(6)
list.insert(2)
list.insert(7)
list.insert(1)
print(list)