您的位置:首页 > Web前端 > Node.js

nth-to-last-node-in-list

2015-07-02 10:58 756 查看


Easy Nth
to Last Node in List
Show result

44%

Accepted

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

Have you met this question in a real interview?

Yes

Example

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) {
        if(head == null || head.next == null){
            return head;
        }
        int length = 1;
        ListNode dummy = head;
        while(head.next != null){
            head = head.next;
            length++;
        }
        int count = 0;
        head = dummy;
        while(head != null){
            if(count == length-n){
                return head;
            }
            head = head.next;
            count++;
        }
        return null;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: