nth to last node in list

Find the nth to last element of a singly linked list.
The minimum number of nodes in list is n.

Example
Given a List 3->2->1->5->null and n = 2, return node whose value is 1.

Here is my thought:

Because we can only count the list from the beginning. If we want to find the nth to last node in the list, we need to know the length of the list -- len.
Then the nth to last node in list we be (len- n)th node from the beginning.
Therefore, we need to count 2len - n times.

My solution:


/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: Nth to last node of a singly linked list. 
     */
    ListNode nthToLast(ListNode head, int n) {
        // write your code here
        int len = 0;
        
        ListNode temp = head;
        while (temp != null) {
            len++;
            temp = temp.next;
        }
        
        ListNode node = head;
        
        int counter = 0;
        for (counter = 0; counter < len - n; counter++) {
            node = node.next;
        }
        
        return node;
    }
}

下面的解法精妙之处在于利用了list的长度。
其实list长度是一定的,并且我们并不需要得到这个长度,先数n个node,剩下的就是len-n个node,此时再让另一个变量或指针从list的头开始一起数,等走到最后时,从头数的变量也走到了第len - n 个node,正好是 nth to last node in list.

public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: Nth to last node of a singly linked list. 
     */
    ListNode nthToLast(ListNode head, int n) {
        if (head == null || n < 1) {
            return null;
        }
    
        ListNode p1 = head;
        ListNode p2 = head;
        for (int j = 0; j < n - 1; ++j) {
            if (p2 == null) {
                return null;
            }
            p2 = p2.next;
        }
        while (p2.next != null) {   
            p1 = p1.next;   
            p2 = p2.next;
        }
        return p1;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容