Nth to Last Node in List

Posted YuriFLAG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */ 
12 public class Solution {
13     /**
14      * @param head: The first node of linked list.
15      * @param n: An integer.
16      * @return: Nth to last node of a singly linked list. 
17      */
18     ListNode nthToLast(ListNode head, int n) {
19         if (head == null) {
20             return null;
21         }
22         ListNode front = head;
23         ListNode node = head;
24         while (n > 0) {
25             if (front == null) {
26                 return null;
27             }
28             front = front.next;
29             n--;
30         }
31         while (front != null) {
32             node = node.next;
33             front = front.next;
34         }
35         return node;
36     }
37 }

 

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

leetcode:Nth to Last Node in List

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

166 链表倒数第n个结点

nth-child,nth-last-child,only-child,nth-of-type,nth-last-of-type,only-of-type,first-of-type,last-of-

CSS3中nth-of-type和nth-last-of-type

在 IE 中,这个 :not(:nth-child():nth-last-child()) 声明不起作用