Nth to Last Node in List

Posted 北叶青藤

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.

分析:

要找到nth to last element,我们需要两个指针,第一个指针先走n步,然后两个指针同时走,知道第一个指针为null.

 1 public class Solution {
 2     /**
 3      * @param head: The first node of linked list.
 4      * @param n: An integer.
 5      * @return: Nth to last node of a singly linked list. 
 6      */
 7     ListNode nthToLast(ListNode head, int n) {
 8         if (head == null || n <= 0) return null;
 9         
10         ListNode first = head;
11         ListNode last = head;
12 
13         for (int count = 1; count <= n; count++;) {
14             first = first.next;
15         }
16         
17         while(first != null) {
18             first = first.next;
19             last = last.next;
20         }
21         return last;
22     }
23 }

转载请注明出处:cnblogs.com/beiyeqingteng/

以上是关于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个结点

Remove Nth Node From End of List

leetcode#19 Remove Nth Node From End of List

leetcode 19. Remove Nth Node From End of List