脚本宝典收集整理的这篇文章主要介绍了[LintCode/LeetCode] Nth to Last Node in List,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
Problem
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.
Note
依然是一道找倒数第n个结点的链表题,用双指针做。fast先走n,然后fast和slow一起走,直到fast为null,slow的位置就是倒数第n个位置。
Solution
public class Solution {
ListNode nthToLast(ListNode head, int n) {
ListNode fast = head, slow = head;
int i = n;
while (i-- > 0) fast = fast.next;
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
以上是脚本宝典为你收集整理的[LintCode/LeetCode] Nth to Last Node in List全部内容,希望文章能够帮你解决[LintCode/LeetCode] Nth to Last Node in List所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。