How to find nth element from the end of a singly linked list?

后端 未结 28 1160
感动是毒
感动是毒 2020-12-04 06:08

The following function is trying to find the nth to last element of a singly linked list.

For example:

If the elements are

28条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 06:39

    Use two pointer pTemp and NthNode. Initially, both points to head node of the list. NthNode starts moving only after pTemp made n moves. From the both moves forward until pTemp reaches end of the list. As a result NthNode points to nth node from the end of the linked list.

    public ListNode NthNodeFromEnd(int n){
        ListNode pTemp = head, NthNode = null;
       for(int count=1; count

    Refer TextBook : "Data Structure and Algorithms Made Easy in Java"

提交回复
热议问题