Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Find the n’th Node from the end of a given Linked List

Objec­tive: Given a linked list and inte­ger ‘n’, write an algo­rithm to find the nth node from the end in the Linked List.

Exam­ple:

Original List : ->1->2->8->3->7->0->4
Output : 3rd Element from the end is : 7

Input: An unsorted linked list and inte­ger k

Out­put: The kth to Last Ele­ment of a Singly Linked List

Approach:

Recur­sive Approach:

  • Recurse through the Linked list
  • When we reach to the end of the list, base case will return 0
  • Now with each pass­ing back call through stack, add 1 and return.
  • When count hits k, print the value.


Iter­a­tive Approach:

  • Take two point­ers approach
  • Move first pointer by k
  • now move both the point­ers and when the first pointer reaches the end of the list the sec­ond pointer will be at the kth node from the end.
  • Return the kth node data.

Com­plete Code:


Out­put:

Original List : ->1->2->8->3->7->0->4
Recursion::3rd Element from the end is : 7
Iteration::5th Element from the end is : 8

You may also like...