×

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

Identical Linked Lists

Identical Linked Lists In this problem, we have given two linked lists, and we need to check whether the given linked lists are identical or not. Identical means they have the...

4 minutes read.

Merge Conflicts and ways to handle them

Merge Conflicts Whenever dealing with the Git merge operations, conflicts will be the frequently occurred. When more than two developers work on the same file on different systems using Git, they...

4 minutes read.

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Structure and Union Data Structure

The array is used for the same type of data, but if we want to store a mixed type of data in a group, then the array cannot be used. The Structure...

4 minutes read.

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

3 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Counts the number of times a given element occurs in a Linked List

Counts the number of times a given element occurs in a Linked List This article will explain how we can count the occurrences of a particular element in a list. Here,...

3 minutes read.

Complete Binary tree

In this article, we will discuss the complete binary tree. But before start discussing the complete binary tree, we should first see a brief description of a binary tree. What is...

7 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.

B+ Tree in Data Structure

A B-Tree extension called B+ Tree, which enables effective search, insertion, and deletion operations. Both Records and keys can be stored in internal and leaf nodes in a B tree. Contrarily,...

4 minutes read.

Left View of Binary Tree

Implementation // creating a C++ program to print the Left view of the binary tree. #include <bits/stdc++.h> using namespace std; struct Nod { int record; struct Nod *Lft, *Rt; }; // creating a utility function that will eventually help...

4 minutes read.

Data Structures Algorithms

What is an Algorithm? An algorithm is a sequence of steps used to complete a job or get a desired result. It is similar to programming building elements that let cell...

4 minutes read.

Reverse the Singly Linked List in C

Reverse the Singly Linked List in C This article has given a singly linked list and will reverse the linked list by changing the links between nodes. Example:                         Input:  2 -> 4...

3 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.

Buffer overflow attack with examples

You have undoubtedly faced the term buffer overflow in your programming journey. Many times it occurs when we try to run a piece of code with user input, but it...

4 minutes read.

Data structure: Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

Linked List Representation of Binary Tree

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. The word binary itself represents its meaning; we know that...

4 minutes read.

A Full Binary Tree with n Nodes

Implementation // Writing the implementation of the above approach in C++ #include <bits/stdc++.h> using namespace std; // We are creating a class that will create a node and its left and right children.  struct __nod...

12 minutes read.

Understanding Data Processing

Introduction Data In our everyday lives, any task that we perform online is related to data. Millions of pieces of data are produced every second across the globe. Data production is largely...

4 minutes read.

Given a Binary Tree Return All Root-to-Leaf Paths

Implementation #include <bits/stdc++.h> using namespace std; // A binary tree node generally consists of data, a pointer to the left and right child, and a pointer to the right child.  class __nod { public: int record; __nod* Lft; __nod*...

9 minutes read.