-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patha03.py
145 lines (102 loc) · 3.12 KB
/
a03.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
class Node:
def __init__(self, val=None):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self,val=None):
new_node = Node(val)
if self.head is None: #empty list
self.head = new_node
return
last = self.head
while last.next is not None:
last = last.next
last.next = new_node
def pop(self):
if self.head is None:
raise Exception('List is already empty')
if self.head.next is None:
val = self.head.val
self.head = None
return val
temp = self.head
while temp.next is not None:
prev = temp
temp = temp.next
val = temp.val
prev.next = None
return val
def __str__(self):
ret_str = '['
temp = self.head
while temp:
ret_str += str(temp.val) + ', '
temp = temp.next
ret_str = ret_str.rstrip(', ')
ret_str = ret_str + ']'
return ret_str
def insert(self, index, val):
new_node = Node(val)
if index == 0:
new_node.next = self.head
self.head = new_node
return
temp = self.head
counter = 0
while temp is not None and counter < index:
prev = temp
temp = temp.next
counter += 1
prev.next = new_node
new_node.next = temp
def remove(self, val):
if self.head is None:
raise Exception('List is empty')
temp = self.head
if temp is not None:
if temp.val == val:
self.head = temp.next #or self.head.next
temp = None
return
while temp:
if temp.val == val:
break
prev = temp
temp = temp.next
if temp is None:
return
prev.next = temp.next
def len(self):
temp = self.head
counter = 0
while temp:
temp = temp.next
counter += 1
return counter
def get(self,index):
if index == 0:
return self.head.val
temp = self.head
count = 0
while temp is not None and count<index:
temp = temp.next
count += 1
if count == index:
if temp is not None:
return temp.val
else:
raise IndexError('Index not found')
if count != index:
raise IndexError('Index not found')
if __name__ == "__main__":
l = LinkedList()
l.push(5)
l.push(6)
print(l)
print(l.len())
l.pop()
print(l.len())
print(l.get(0))
l.get(2) # Should say "IndexError: Index out of bound"