Write a program to find Kth element from end in a given linked list. Suppose linked list is as below:
Head -> 1 -> 2 -> 3 -> 4 -> 5
And K = 2
Output
2nd node from end is: 4
Category: Data Structure And Algorithms | Tags: C# |
Write a program to find Kth element from end in a given linked list. Suppose linked list is as below:
Head -> 1 -> 2 -> 3 -> 4 -> 5
And K = 2
Output
2nd node from end is: 4
Answers:
We can solve this problem by keeping two pointers. First pointer starts at head and another pointer called forward pointer which is already forwarded to Kth node from head. So when we traverse the linked list we forward each pointer by one node thus first pointer always be behind kth position from forward pointer. Once forward pointer reaches to end first pointer will give us Kth element from end. Look at the code below.
Let's run above code.
Output
2th node from end is: 4