
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Kth Node from the end in a given singly Linked List using C++
A linked list is a linear data structure that has multiple nodes that are connected with each other. Each node consists of two fields Data Field and address of the next node. Let us assume we have given a singly linked list the task is to find the kth node from the end in a given singly linked list. For example,
Input β
1β2β3β4β7β8β9 K= 4
Output β
Node from the 4th Position is β 4
Explanation β Since in the given singly linked list β4thβ node from the end is β4β, we will return the output as β4β.
Approach to solve this problem
Initially, we have given a linked list that consists of nodes. Each node contains the data and address to the next node. So, to find the kth node from the end, we will take two pointers which initially points to the head of the linked list.
While iterating over the linked list, we will move one of the pointers letβs say βfastβ, and then move the other pointer until the βfastβ pointer doesn't reach the end.
A Function kthNodefromTheEnd(node*head, int pos) takes the pointer to the head node and the position as a parameter and returns the node from the end.
Letβs take two pointers βslowβ and βfastβ which are initially at the head.
Iterate over the linked list and move the fast pointer.
Since the βfastβ pointer is two steps ahead of βslowβ let us move both pointers until βfastβ reaches the end.
Now return the value at slow which points to the kth node from the end.
Example
#include<iostream> using namespace std; class node{ public: int data; node*next; node(int d){ data=d; next=NULL; } }; void insertAthead(node*&head,int d){ node*n= new node(d); n->next= head; head=n; } void printList(node*head){ while(head!=NULL){ cout<<head->data<<"-->"; head= head->next; } } void kthFromtheEnd(node*head, int k){ node*slow= head; node*fast= head; for(int i=0;i<k;i++){ fast= fast->next; } while(fast!=NULL){ slow= slow->next; fast= fast->next; } cout<<"Node from the "<<k<<"th position is"<<slow->data<<endl; } int main(){ node*head= NULL; insertAthead(head,2); insertAthead(head,4); insertAthead(head,5); insertAthead(head,6); insertAthead(head,7); printList(head); cout<<endl; kthFromtheEnd(head,4); return 0; }
Output
Running the above code will generate the output as,
Node from the 4th position is: 6
Explanation β The given linked list is 7β 6β 5β 4β 2β and the kth value is β4β. So, the 4th node from the end is β6β, thus we will return β6β.