# Find the Kth Node from the end in a given singly Linked List using C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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

Live Demo

#include<iostream>
using namespace std;
class node{
public:
int data;
node*next;
node(int d){
data=d;
next=NULL;
}
};
node*n= new node(d);
}
}
}
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(){
cout<<endl;
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’.

Updated on 05-Feb-2021 12:08:35