lintcode-easy-Nth to Last Node in List Show result

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-easy-Nth to Last Node in List Show result相关的知识,希望对你有一定的参考价值。

Find the nth to last element of a singly linked list. 

The minimum number of nodes in list is n.

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

 

/**
 * 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
        ListNode fast = head;
        for(int i = 0; i < n; i++)
            fast = fast.next;
        
        ListNode slow = head;
        
        while(fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        
        return slow;
    }
}

 

以上是关于lintcode-easy-Nth to Last Node in List Show result的主要内容,如果未能解决你的问题,请参考以下文章

LINQ To Entities 无法识别方法 Last。真的吗?

Nth to Last Node in List

javascript last_word_wrap_to_span.js

Nth to Last Node in List

leetcode:Nth to Last Node in List

How to check the last commit is matched with version