×

Find the nth node from the end of a Linked List

Find the nth node from the end of a Linked List

In this problem, we have given a singly linked list and a number 'n,' and we need to find the nth node from the end of the linked list and return it.

Example:

List:

13  ->  16  ->  9  ->  10  ->  4  ->  6  ->  1  ->  3, n = 3

 Output:

6

Method 1: Using length of linked list

  • Firstly, we need to find the length of linked list.
  • Then, we will print the (length – n +1)th node from the beginning of the linked list.

Source code to implement this method using C programming:

 #include<stdio.h>
 #include<stdlib.h>
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start = NULL; int len=0, n;
 // For inserting the elements in the linked list
 void add(int item)
 {
 struct node * t, * p;
 t = (struct node * )malloc( sizeof( struct node ));
 if(start == NULL)
 {
 start = t;
 start -> info = item;
 start -> next = NULL;
 return;
 }
 else
 {
 struct node * p = start;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // For finding the length of the linked list
 void length(struct node * temp)
 {
             while(temp != NULL)
             {
                         len += 1;
                         temp = temp -> next;
             }
 }
 // For finding the nth node from the end of a Linked List
 struct node * findNode(struct node * temp)
 {
             int i;
             length(temp);
             int j = (len - n + 1);
            for(i = 0; i < j-1; i++)
             {
                         temp = temp -> next;
             }
             return temp;
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
                                     }
                                     while(t -> next != NULL)
                                     {
                         printf("%d -> ", t -> info);
                         t = t -> next;
                         }
                         printf("%d\n", t -> info);
 }
 // Driver Function
 int main()
 {
     int i;
     printf("which node you want to search from last:");
     scanf("%d", &n);
     for (i = 2; i < 12; i+=2)
     {
         add(i);
     }
     printf("Linked List is:");
     traverse(start);
     printf("node is:%d", findNode(start) -> info);
     return 0;
 } 

Output:

Find the nth node from the end

Time Complexity: The time complexity of the above method is O(n).

Method 2: Using two pointers

In this method, we will maintain two pointers – the first is the reference pointer, and the second is the main pointer. Next, we will initialize both reference and main pointers to the starting address of the linked list. Next, we will first move the reference pointer to n nodes from the head and then move both pointers one by one until the reference pointer reaches the end. Now, the main pointer will point to the nth node from the end. Finally, it will return the main pointer.

Source code to implement this method using C programming:

 #include<stdio.h>
 #include<stdlib.h>
 struct node
 {
 int info;
 struct node *next;
 };
 struct node *start = NULL; int len = 0, n;
 // For inserting the elements in the linked list
 void add(int item)
 {
 struct node * t, * p;
 t = (struct node * )malloc( sizeof( struct node ));
 if(start == NULL)
 {
 start = t;
 start -> info = item;
 start -> next = NULL;
 return;
 }
 else
 {
 struct node * p = start;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // For finding the nth node from the end of a Linked List
 void nodeFromLast(struct node * temp)
 {
   struct node * main_ptr = temp;
   struct node * ref_ptr = temp;
   int count = 0;
   if(temp != NULL)
   {
      while(count < n)
      {
         if(ref_ptr == NULL)
         {
            printf("%d is greater than the no. of "
                     "nodes in list", n);
            return;
         }
         ref_ptr = ref_ptr -> next;
         count++;
      }
      if(ref_ptr == NULL)
      {
         temp = temp -> next;
         if(temp != NULL)
             printf("Node no. %d from last is %d ", n, main_ptr -> info);
      }
      else
      {
        while(ref_ptr != NULL)
        {
           main_ptr = main_ptr -> next;
           ref_ptr  = ref_ptr -> next;
        }
        printf("Node no. %d from last is %d ", n, main_ptr -> info);
      }
   }
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
                                     }
                                     while(t -> next != NULL)
                                     {
                         printf("%d -> ", t -> info);
                         t = t -> next;
                         }
                         printf("%d\n", t -> info);
 }
 // Driver Function
 int main()
 {
     int i;
     printf("which node you want to search from last: ");
     scanf("%d", &n);
     for (i = 2; i < 12; i+=2)
     {
         add(i);
     }
     printf("Linked List is:");
     traverse(start);
     nodeFromLast(start);
     return 0;
 } 

Output:

Find the nth node from the end

Time Complexity: The time complexity of the above method is O(n).


Related Topics

Write Main Difference Between Tree and Graph in Data Structures

Graph: The graph has two sets, which are considered V and E. These vertices are also called nodes, and edges are referred to as arcs connecting any two nodes in a...

4 minutes read.

Tim Sort

Tim Sort is a mixture stable arranging calculation that exploits normal examples in information, and uses a mix of an improved Merge sort and Binary Insertion sort alongside an interior...

6 minutes read.

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are...

4 minutes read.

Quick Sort

Quicksort is a sorting algorithm that uses a divide-and-conquer strategy. A pivot element is used to divide an array into subarrays (element selected from the array).  The pivot element should be...

4 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 minutes read.

Stack vs Queue: Data Structure

 Difference Between Stack and Queue What is Stack? The LIFO principle applies on insertion and deletion operations of the stack which means last inserted element to the stack will remove first....

3 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

Stack Data Structure

The stack is a non-primitive and linear data structure. It works on the principle of LIFO (Last In First Out). That is, the element that is added to the end...

3 minutes read.

CSS Text-indent

Text-indent The Text-indent property of CSS is used to set any first line’s indentation inside a text’s block. It describes the horizontal space amount that puts establish before the text line. It...

3 minutes read.

Collision Resolution Techniques

Collision Resolution Techniques Collision in hashing In this, the hash function is used to compute the index of the array.The hash value is used to store the key in the hash table,...

2 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 minutes read.

Bucket Sort

Bucket Sort: In the sorting algorithm, we create buckets and put elements into them. We can apply some sorting algorithm (insertion sort) to sort the elements in each bucket. Finally,...

4 minutes read.

Blowfish algorithm

The Blowfish algorithm is the very first encryption algorithm which is symmetric. It was firstly used as an alternate algorithm for the DES algorithm. It was designed by Bruce Steiner...

3 minutes read.

Application of 2D array - Sparse Matrix

2D Arrays Application - Sparse Matrix A matrix is a two-dimensional data item consisting of m rows and n columns, with a total of m x n values. A sparse matrix...

7 minutes read.

Implementation of stack

Implementation of stack: The stack can be implemented in two ways: using array and using a linked list. The pop and push operations in the array are simpler than the...

3 minutes read.

Fundamental of Algorithms

An algorithm is a part of any programming solution or coding. If we have to make a solution then first we have to think of a clear idea about the...

13 minutes read.

Lowest Common Ancestor in a Binary Tree

The lowest node in the tree that contains both n1 and n2 as descendants is the lowest common ancestor (LCA), and n1 and n2 are the nodes for which we...

11 minutes read.

Red Black Tree

Red Black Tree A red-black tree is referred as self-balancing binary search tree. The tree was invented by Rudolf Bayer in 1972. In red-black, each node stores an extra bit that...

8 minutes read.

Treap data structure

In this article, we will discuss the treap data structure. The word treap is a combination of 'tree' and 'heap'. So, treap data structure is a combination of a heap...

8 minutes read.