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

[刷题]Nth to Last Node in List

2015-08-28 15:18 483 查看
[LintCode]Nth to Last Node in List

/**
* Definition for ListNode.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int val) {
*         this.val = val;
*         this.next = 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) {
// 2015-08-28
if (head == null) {
return null;
}

ListNode fast = head;
ListNode slow = head;

for (int i = 0; i < n; i++) {
fast = fast.next;
}

while (fast != null) {
slow = slow.next;
fast = fast.next;
}

return slow;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: