i am curious if there is a better way to find an item at a given position of a linked list whose size in not known.
example:
1->2->3->4->5->6->7->8->9->10->null.
if this my link-list, and i am asked to print the value of 6th node and initially, i don't know the length of list as well.
my solution.. i can iterate through each node until i reach the 6th node.
my question is, is there any other way to reach 6th node ? if yes, how much time/memory it can save on an average ?
CodePudding user response:
No - with a linked list there is no better option.
There are data structures similar to linked lists which can find the nth item in O(log n), such as skip lists and binary trees. However, in most cases it's a better idea to replace the linked list with a dynamic array.