Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python Program For Writing A Function To Get Nth Node In A Linked List

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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




# A complete working Python program to
# find n'th node in a linked list
 
# Node class
class Node:
    # Function to initialize the node object
    def __init__(self, data):
 
        # Assign data
        self.data = data 
 
        # Initialize next as null
        self.next = None 
 
# Linked List class contains a Node object
class LinkedList:
 
    # Function to initialize head
    def __init__(self):
        self.head = None
 
    # This function is in LinkedList class.
    # It inserts a new node at the beginning
    # of Linked List.
    def push(self, new_data):
 
        # 1 & 2: Allocate the Node &
        #        Put in the data
        new_node = Node(new_data)
 
        # 3. Make next of new Node as head
        new_node.next = self.head
 
        # 4. Move the head to point to new Node
        self.head = new_node
 
    # Returns data at given index in linked list
    def getNth(self, index):
 
        # Initialise temp
        current = self.head 
 
        # Index of current node
        count = 0 
 
        # 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
 
 
# Driver Code
if __name__ == '__main__':
 
    llist = LinkedList()
 
    # Use push() to construct list
    # 1->12->1->4->1
    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




# Python3 program to find n'th node in
# linked list using recursion
 
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
class LinkedList:
    def __init__(self):
        self.head = None
 
    # Given a reference (pointer to pointer) to
    # the head of a list and an int, push a new
    # node on the front of the list.
 
    # Make new node and add
    # into LinkedList
    def push(self, new_data):                               
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node
 
    def getNth(self, llist, position):
 
        # Call recursive method
        llist.getNthNode(self.head,
                         position, llist)
 
    # Recursive method to find Nth Node
    def getNthNode(self, head, position, llist):
 
        # Initialize count
        count = 0 
        if(head):
 
            # If count is equal to position,
            # it means we have found the position
            if count == position: 
                                   
                print(head.data)
            else:
                llist.getNthNode(head.next,
                                 position - 1, llist)
        else
            # If head doesn't exist we have
            # traversed the LinkedList
            print('Index Doesn\'t exist')
 
# Driver Code
if __name__ == "__main__":
    llist = LinkedList()
    llist.push(1)
    llist.push(4)
    llist.push(1)
    llist.push(12)
    llist.push(1)
 
    # llist.getNth(llist,int(input()))
    # Enter the node position here
    # First argument is instance of LinkedList
 
    print("Element at Index 3 is", end = " ")
    llist.getNth(llist, 3)
# This code is contributed by Yogesh Joshi


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!
 


My Personal Notes arrow_drop_up
Last Updated : 31 Jul, 2022
Like Article
Save Article
Similar Reads
Related Tutorials