Hi plss help I already posted twice!! How to access node from any index in linke
ID: 3717873 • Letter: H
Question
Hi plss help I already posted twice!!
How to access node from any index in linked list implementation?Hi I've written a method to get a node from a specific index but I just realised it doesn't work for negative indexes say I want to access the node at list[-1]?How do I modify it?Self.count refers to the next available position in list
def _get_node(self, index):
assert 0< =index <self.count "Index out of bounds"
node=self.head
for _ in range(index):
node=node.next
return node
Explanation / Answer
def getanynode(self, index):
current = self.head # start from head node
count = 0 # Index of current node
# Loop while end of linked list is not reached
while (current):
if (count == index):
return current.data
count += 1
current = current.next
# if we get to this line, the caller was asking
# for a non-existent element so we assert fail
assert(false)
return 0;
this is simle code for i used in my link list hope it will work for u.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.