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

后端 未结 28 1108
感动是毒
感动是毒 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:36

    To understand this problem, we should do a simple analogy with a measurement example. Let's say, you have to find the place of your arm where exactly 1 meter away from your middle finger, how would you measure? You would just grab a ruler with a 1-meter length and put the top-end of that ruler to the tip of your middle-finger and the bottom-end of the meter will be exactly 1 meter away from the top of your middle-finger.

    What we do in this example will be the same, we just need a frame with n-element wide and what we have to do is put the frame to the end of the list, thus the start node of the frame will be exactly n-th element to the end of the list.

    This is our list assuming we have M elements in the list, and our frame with N element wide;

    HEAD -> EL(1) -> EL(2) -> ... -> EL(M-1) -> EL(M)
    
    <-- Frame -->
    

    However, we only need the boundaries of the frame, thus the end boundary of the frame will exactly (N-1) elements away from the start boundary of the frame. So have to only store these boundary elements. Let's call them A and B;

    HEAD -> EL(1) -> EL(2) -> ... -> EL(M-1) -> EL(M)
    
    A <- N-Element Wide-> B
    

    The first thing we have to do is finding B, which is the end of the frame.

    ListNode b = head;
    int count = 1;
    
    while(count < n && b != null) {
        b = b.next;
        count++;
    }
    

    Now b is the n-th element of the array, and a is located on the HEAD. So our frame is set, what we will do is increment both boundary nodes step by step until b reachs to the end of the list where a will be n-th-to-the-last element;

    ListNode a = head;
    
    while(b.next != null) {
        a = a.next;
        b = b.next;
    }
    
    return a;
    

    To gather up everything, and with the HEAD checks, N < M (where M is the size of the list) checks and other stuff, here is the complete solution method;

    public ListNode findNthToLast(int n) {
        if(head == null) {
            return null;
        } else {
            ListNode b = head;
            int count = 1;
    
            while(count < n && b != null) {
                b = b.next;
                count++;
            }
    
            if(count == n && b!=null) {
                ListNode a = head;
    
                while(b.next != null) {
                    a = a.next;
                    b = b.next;
                }
    
                return a;
            } else {
                System.out.print("N(" + n + ") must be equal or smaller then the size of the list");
                return null;
            }
        }
    }
    

提交回复
热议问题