Recently started solving leetcode problems and I tried to implement a linked list but I keep getting a time limit exceeded error. How can I solve this? The code runs perfectly well on sample input cases but I think it fails on edge cases. After going through various variations of code I haven't come up with a better way to implement a linked list. Here is my code
class Node:
def __init__(self,data):
self.data = data
self.next = None
class MyLinkedList:
def __init__(self):
self.head =None
def get(self, index: int) -> int:
temp = self.head
if index == 0:
return temp.data
pos = 0
while temp is not None:
if pos == index:
return temp.data
break
# return temp.data
temp = temp.next
pos+=1
if temp == None:
return -1
def addAtHead(self, val: int) -> None:
new_node = Node(val)
new_node.next = self.head
self.head = new_node
def addAtTail(self, val: int) -> None:
new_node = Node(val)
temp = self.head
if self.head is None:
self.head = new_node
while temp.next is not None:
temp = temp.next
temp.next =new_node
def addAtIndex(self, index: int, val: int) -> None:
new_node = Node(val)
temp = self.head
if index ==0:
new_node.next=temp
self.head = new_node
pos = 0
while temp is not None:
if pos == index:
break
prev = temp
temp = temp.next
pos+=1
prev.next =new_node
new_node.next=temp
def deleteAtIndex(self, index: int) -> None:
if self.head is None:
return -1
if index ==0:
self.head = self.head.next
return self.head
pos =0
curr = self.head
prev=self.head
temp = self.head
while curr is not None:
if pos == index:
temp = curr.next
break
prev = curr
curr =curr.next
pos+=1
prev.next=temp
return prev
And here is a sample input test case:
["MyLinkedList","addAtHead","addAtHead","addAtHead","addAtIndex","deleteAtIndex","addAtHead","addAtTail","get","addAtHead","addAtIndex","addAtHead"]
[[],[7],[2],[1],[3,0],[2],[6],[4],[4],[4],[5,0],[6]]
addAtIndexlooks like it's wrong, because it setsprev.nextandnew_node.nexton every iteration while it's finding the index. I haven't debugged further, but I guess somehow you end up with a circular linked list in some case and that's why you're getting timeouts. I suggest testing your code thoroughly with unit tests.