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

Lintcode: Nth to Last Node in List

时间:2015-04-02 06:34:52      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

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.

Runner Technique: 两个指针都从Dummy node出发,结束条件是runner.next!=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         // write your code here
 9         ListNode dummy = new ListNode(0);
10         dummy.next = head;
11         ListNode walker = dummy;
12         ListNode runner = dummy;
13         while (runner.next != null && n>0) {
14             runner = runner.next;
15             n--;
16         }
17         while (runner.next != null) {
18             runner = runner.next;
19             walker = walker.next;
20         }
21         return walker.next;
22     }
23 }

 

Lintcode: Nth to Last Node in List

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/4385805.html

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