python
class ListNode:
def __init__(self,val=0,next=None):
self.val=val
self.next=next
class MyLinkedList:
def __init__(self):
self.head=None
self.size=0
def get(self, index: int) -> int:
if index<0 or index>=self.size:
return -1
current_node=self.head
for _ in range(index):
current_node=current_node.next
return current_node.val
def addAtHead(self, val: int) -> None:
self.head=ListNode(val,self.head)
self.size+=1
def addAtTail(self, val: int) -> None:
if not self.head:
self.addAtHead(val)
return
current_node=self.head
while current_node.next:
current_node=current_node.next
current_node.next=ListNode(val)
self.size+=1
def addAtIndex(self, index: int, val: int) -> None:
if index>self.size:
return
if index<=0:
self.addAtHead(val)
return
current_node=self.head
for _ in range(index-1):
current_node=current_node.next
current_node.next=ListNode(val, current_node.next)
self.size+=1
def deleteAtIndex(self, index: int) -> None:
if index<0 or index>=self.size:
return
self.size-=1
if index==0:
self.head=self.head.next
else:
current_node=self.head
for _ in range(index-1):
current_node=current_node.next
current_node.next=current_node.next.next
# 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)