码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-03-03 07:58:08      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5237178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!