Find the Nth Node from the End of a Linked List in C++

This C++ program demonstrates how to find the nth node from the end of a linked list using the two-pointer (or fast and slow pointer) technique, which is efficient and only requires a single pass through the list.

Program Code


#include <iostream>

// Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// Function to find the nth node from the end of a linked list
ListNode* findNthFromEnd(ListNode* head, int n) {
    ListNode *fast = head, *slow = head;

    // Move fast pointer n steps ahead
    for (int i = 0; i < n; i++) {
        if (fast == NULL) return NULL;  // n is larger than the number of nodes in the list
        fast = fast->next;
    }

    // Move fast to the end, maintaining the gap
    while (fast != NULL) {
        fast = fast->next;
        slow = slow->next;
    }

    return slow;
}

// Helper function to print the linked list
void printList(ListNode* node) {
    while (node != NULL) {
        std::cout << node->val << " ";
        node = node->next;
    }
    std::cout << std::endl;
}

int main() {
    // Create a linked list: 1->2->3->4->5
    ListNode* a = new ListNode(1);
    a->next = new ListNode(2);
    a->next->next = new ListNode(3);
    a->next->next->next = new ListNode(4);
    a->next->next->next->next = new ListNode(5);

    // Find the 2nd node from the end
    ListNode* result = findNthFromEnd(a, 2);
    if (result != NULL) {
        std::cout << "The 2nd node from the end is: " << result->val << std::endl;
    } else {
        std::cout << "Invalid position!" << std::endl;
    }

    return 0;
}

Explanation of the Code

The program starts by defining a struct for the singly-linked list node. The main functionality is encapsulated in the findNthFromEnd function, which uses two pointers: fast and slow. The fast pointer advances n steps ahead of the slow pointer. Once the fast pointer is n steps ahead, both pointers advance at the same rate until the fast pointer reaches the end of the list. At this point, the slow pointer will be at the nth node from the end.

This two-pointer method is efficient as it traverses the list only once, and it is particularly useful in situations where the list size is unknown or the list is too long to traverse multiple times.

Conclusion

This program effectively demonstrates a common technique for solving problems related to linked lists, making it a useful snippet for many C++ developers working with data structures.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)