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

Nth to Last Node in List

2016-07-03 03:51 363 查看
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.

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 || n <= 0) return null;

ListNode first = head;
ListNode last = head;

for (int count = 1; count <= n; count++;) {
first = first.next;
}

while(first != null) {
first = first.next;
last = last.next;
}
return last;
}
}


转载请注明出处:cnblogs.com/beiyeqingteng/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: