In one
of my previous post I discussed a method to find the middle element of the
linked list in single traversal using 2 pointers. In this post We will see a
similar approach to find the kth element from the end of the linked list.
Finding
the kth element from the end of the linked list is one of the famous interview
questions and is asked a lot.
In
order to find the kth element from the end of the linked list we use 2 pointers.
Let the 2 pointers be first and second. now we initialize them to point at the head
node of the linked list and move the second pointer to the kth node. After that
we start traversing the linked list using both the pointer and keep moving them
forward until the first pointer reaches the end of the linked list. as the
difference between the position of the pointers is k places when the first node
points the last node then the second pointer will point to the kth element from
the end. So we can simply return the second pointer or the contents of the the
node pointed by the second pointer.
The
idea is to have a difference of k places between the first and the second
pointers. using this method, we can find the kth element from the end in a
single
traversal
and we do not need to traverse the linked list twice.
So time
complexity of this approach is o(n) and space complexity is o(1).
Algorithm:
- Initialize 2 pointers first and second to head node
- Move node first to the kth node from the start
- Move both first and second node through the list till first node reaches the last node
- At this point the second node points to the kth node from the end
- Return the contents of the second node
Code :
C++ Program
Sample input and output to check the program
You might also be interested in
Singly Linked List
Double Linked List
Linked List in Python
Stack Implementation using Linked List
Queue Implementation using Linked List
Vigenere Cipher Encryption
Check for Anagram Strings
Comments
Post a Comment