-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdesigned-linkedlist.py
62 lines (49 loc) · 1.51 KB
/
designed-linkedlist.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
class Node:
def __init__(self, val):
self.val = val
self.next = None
class MyLinkedList:
def __init__(self):
self._head = Node(0)
self._count = 0
def get(self, index: int) -> int:
if 0 <= index < self._count:
node = self._head
for _ in range(index + 1):
node = node.next
return node.val
else:
return -1
def addAtHead(self, val: int) -> None:
self.addAtIndex(0, val)
def addAtTail(self, val: int) -> None:
self.addAtIndex(self._count, val)
def addAtIndex(self, index: int, val: int) -> None:
if index < 0:
index = 0
elif index > self._count:
return
self._count += 1
add_node = Node(val)
prev, cur = None, self._head
for _ in range(index + 1):
prev, cur = cur, cur.next
else:
prev.next, add_node.next = add_node, cur
def deleteAtIndex(self, index: int) -> None:
if 0 <= index <= self._count:
self._count -= 1
prev, cur = None, self._head
for _ in range(index + 1):
prev, cur = cur, cur.next
else:
prev.next, cur.next = cur.next, None
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
a = MyLinkedList()
print(a.addAtHead(3))