Python Program For Writing A Function To Get Nth Node In A Linked List
Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position.
Example:
Input: 1->10->30->14, index = 2
Output: 30
The node at index 2 is 30
Algorithm:
1. Initialize count = 0
2. Loop through the link list
a. If count is equal to the passed index then return
current node
b. Increment count
c. change current to point to next of the current.
Implementation:
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def push( self , new_data):
new_node = Node(new_data)
new_node. next = self .head
self .head = new_node
def getNth( self , index):
current = self .head
count = 0
while (current):
if (count = = index):
return current.data
count + = 1
current = current. next
assert (false)
return 0
if __name__ = = '__main__' :
llist = LinkedList()
llist.push( 1 )
llist.push( 4 )
llist.push( 1 )
llist.push( 12 )
llist.push( 1 )
n = 3
print ( "Element at index 3 is :" ,
llist.getNth(n))
|
Output:
Element at index 3 is 4
Time Complexity: O(n)
Space Complexity: O(1) because using constant variables
Method 2- With Recursion:
Algorithm:
getnth(node,n)
1. Initialize count = 0
2. if count==n
return node->data
3. else
return getnth(node->next,n-1)
Implementation:
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def push( self , new_data):
new_node = Node(new_data)
new_node. next = self .head
self .head = new_node
def getNth( self , llist, position):
llist.getNthNode( self .head,
position, llist)
def getNthNode( self , head, position, llist):
count = 0
if (head):
if count = = position:
print (head.data)
else :
llist.getNthNode(head. next ,
position - 1 , llist)
else :
print ( 'Index Doesn\'t exist' )
if __name__ = = "__main__" :
llist = LinkedList()
llist.push( 1 )
llist.push( 4 )
llist.push( 1 )
llist.push( 12 )
llist.push( 1 )
print ( "Element at Index 3 is" , end = " " )
llist.getNth(llist, 3 )
|
Output:
Element at index 3 is 4
Time Complexity: O(n)
Auxiliary Space: O(n) due to recursive call stack
Please refer complete article on Write a function to get Nth node in a Linked List for more details!
Last Updated :
17 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...