Write 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
Program for n’th node from the end of a Linked List
Given a Linked List and a number n, write a function that returns the value at the n’th node from the end of the Linked List.
For example, if the input is below list and n = 3, then output is “B”
Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.
Method 1 [Use length of linked list]
1] Calculate the length of Linked List. Let the length be len.
2] Print the [len – n + 1]th node from the beginning of the Linked List.
Double pointer concept : First pointer is used to store the address of the variable and second pointer used to store the address of the first pointer. If we wish to change the value of a variable by a function, we pass pointer to it. And if we wish to change value of a pointer [i. e., it should start pointing to something else], we pass pointer to a pointer.
Below is the implementation of the above approach:
C++14
// Simple C++ program to find n'th node from end #include using namespace std; /* Link list node */ struct Node { int data; struct Node* next; }; /* Function to get the nth node from the last of a linked list*/ void printNthFromLast[struct Node* head, int n] { int len = 0, i; struct Node* temp = head; // count the number of nodes in Linked List while [temp != NULL] { temp = temp->next; len++; } // check if value of n is not // more than length of the linked list if [len < n] return; temp = head; // get the [len-n+1]th node from the beginning for [i = 1; i < len - n + 1; i++] temp = temp->next; cout data; return; } void push[struct Node** head_ref, int new_data] { /* allocate node */ struct Node* new_node = new Node[]; /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = [*head_ref]; /* move the head to point to the new node */ [*head_ref] = new_node; } // Driver Code int main[] { /* Start with the empty list */ struct Node* head = NULL; // create linked 35->15->4->20 push[&head, 20]; push[&head, 4]; push[&head, 15]; push[&head, 35]; printNthFromLast[head, 4]; return 0; } |
Java
// Simple Java program to find n'th node from end of linked list class LinkedList { Node head; // head of the list /* Linked List node */ class Node { int data; Node next; Node[int d] { data = d; next = null; } } /* Function to get the nth node from the last of a linked list */ void printNthFromLast[int n] { int len = 0; Node temp = head; // 1] count the number of nodes in Linked List while [temp != null] { temp = temp.next; len++; } // check if value of n is not more than length of // the linked list if [len < n] return; temp = head; // 2] get the [len-n+1]th node from the beginning for [int i = 1; i < len - n + 1; i++] temp = temp.next; System.out.println[temp.data]; } /* Inserts a new Node at front of the list. */ public void push[int new_data] { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node[new_data]; /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /*Driver program to test above methods */ public static void main[String[] args] { LinkedList llist = new LinkedList[]; llist.push[20]; llist.push[4]; llist.push[15]; llist.push[35]; llist.printNthFromLast[4]; } } // This code is contributed by Rajat Mishra |
Python3
# Simple Python3 program to find # n'th node from end class Node: def __init__[self, new_data]: self.data = new_data self.next = None
class LinkedList: def __init__[self]: self.head = None # createNode and make linked list def push[self, new_data]: new_node = Node[new_data] new_node.next = self.head self.head = new_node # Function to get the nth node from # the last of a linked list def printNthFromLast[self, n]: temp = self.head # used temp variable
length = 0 while temp is not None: temp = temp.next length += 1
# print count if n > length: # if entered location is greater # than length of linked list print['Location is greater than the' + ' length of LinkedList'] return temp = self.head for i in range[0, length - n]: temp = temp.next print[temp.data] # Driver Code llist = LinkedList[] llist.push[20] llist.push[4] llist.push[15] llist.push[35] llist.printNthFromLast[4] # This code is contributed by Yogesh Joshi |
C#
// C# program to find n'th node from end of linked list using System; public class LinkedList { public Node head; // head of the list /* Linked List node */ public class Node { public int data; public Node next; public Node[int d] { data = d; next = null; } } /* Function to get the nth node from the last of a linked list */ void printNthFromLast[int n] { int len = 0; Node temp = head; // 1] count the number of nodes in Linked List while [temp != null] { temp = temp.next; len++; } // check if value of n is not more than length of // the linked list if [len < n] return; temp = head; // 2] get the [len-n+1]th node from the beginning for [int i = 1; i < len - n + 1; i++] temp = temp.next; Console.WriteLine[temp.data]; } /* Inserts a new Node at front of the list. */ public void push[int new_data] { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node[new_data]; /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /*Driver code */ public static void Main[String[] args] { LinkedList llist = new LinkedList[]; llist.push[20]; llist.push[4]; llist.push[15]; llist.push[35]; llist.printNthFromLast[4]; } } // This code is contributed by Rajput-Ji |
Javascript
// Simple Javascript program to find n'th node from end of linked list /* Linked List node */ class Node {
constructor[d] { this.data = d; this.next = null; } } /* Function to get the nth node from the last of a linked list */ class LinkedList { constructor[d]{ this.head = d; }
printNthFromLast[n] { let len = 0; let temp = this.head; // 1] count the number of nodes in Linked List while [temp != null] { temp = temp.next; len++; } // check if value of n is not more than length of // the linked list if [len < n] return; temp = this.head; // 2] get the [len-n+1]th node from the beginning for [let i = 1; i < len - n + 1; i++] temp = temp.next; document.write[temp.data]; } /* Inserts a new Node at front of the list. */ push[new_data] { /* 1 & 2: Allocate the Node & Put in the data*/ let new_node = new Node[new_data]; /* 3. Make next of new Node as head */ new_node.next = this.head; /* 4. Move the head to point to new Node */ this.head = new_node; } }
/*Driver program to test above methods */ let llist = new LinkedList[]; llist.push[20]; llist.push[4]; llist.push[15]; llist.push[35]; llist.printNthFromLast[4];
// This code is contributed by Saurabh Jaiswal |
Output 35
Following is a recursive C code for the same method. Thanks to Anuj Bansal for providing following code.
C++
void printNthFromLast[struct Node* head, int n] { int i = 0; if [head == NULL] return; printNthFromLast[head->next, n]; if [++i == n] coutnext, n]; if [++i == n] printf["%d", head->data]; } |
Java
static void printNthFromLast[Node head, int n] { int i = 0; if [head == null] return; printNthFromLast[head.next, n]; if [++i == n] System.out.print[head.data]; } // This code is contributed by rutvik_56. |
Python3
def printNthFromLast[head, n]:
i = 0 if [head == None] return printNthFromLast[head.next, n]; i+=1 if [i == n]: print[head.data]
# This code is contributed by sunils0ni. |
C#
static void printNthFromLast[Node head, int n] { static int i = 0; if [head == null] return; printNthFromLast[head.next, n]; if [++i == n] Console.Write[head.data]; } // This code is contributed by pratham76. |
Javascript
function printNthFromLast[head , n] { function i = 0; if [head == null] return; printNthFromLast[head.next, n]; if [++i == n] document.write[head.data]; } // This code is contributed by gauravrajput1 |
Time Complexity: O[n] where n is the length of linked list.
Method 2 [Use two pointers]
Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First, move the reference pointer to n nodes from head. Now move both pointers one by one until the reference pointer reaches the end. Now the main pointer will point to nth node from the end. Return the main pointer.
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
C++
// C++ program to find n-th node // from the end of the linked list. #include using namespace std; struct node { int data; node* next; node[int val] { data = val; next = NULL; } }; struct llist { node* head; llist[] { head = NULL; } // insert operation at the beginning of the list. void insertAtBegin[int val] { node* newNode = new node[val]; newNode->next = head; head = newNode; } // finding n-th node from the end. void nthFromEnd[int n] { // create two pointers main_ptr and ref_ptr // initially pointing to head. node* main_ptr = head; node* ref_ptr = head; // if list is empty, return if [head == NULL] { cout 20->30->40->50->60->NULL Node no. 1 from end is: 60 Node no. 2 from end is: 50 Node no. 3 from end is: 40 Node no. 4 from end is: 30 Node no. 5 from end is: 20 Node no. 6 from end is: 10 7 is greater than no. of nodes in the list Time Complexity: O[n] where n is the length of linked list. Article Tags : Linked List Accolite Adobe Amazon Citicorp Epic Systems FactSet Hike Linked Lists MAQ Software Monotype Solutions Qualcomm Snapdeal Practice Tags : Accolite Amazon Snapdeal FactSet Hike MAQ Software Adobe Qualcomm Epic Systems Citicorp Monotype Solutions Linked List Read Full Article C++
|