赞
踩
题目描述:
https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci/
Java代码一:
class Solution { public int getNodeSum(ListNode head){ int sum=0; while(head!=null){ head=head.next; sum++; } return sum; } public int kthToLast(ListNode head, int k) { int count=getNodeSum(head)-k; while(count-->0){ head=head.next; } return head.val; } }
Java代码二:快慢指针
class Solution {
public int kthToLast(ListNode head, int k) { //首末重合
ListNode fast=head,slow=head;
while(k-->0)fast=fast.next; //走k步
if(fast==null)return head.val; //特判
while(fast!=slow){
slow=slow.next;
fast=fast.next==null?head:fast.next;
fast=fast.next==null?head:fast.next;
}
return fast.val; //slow.val亦可
}
}
Java代码三:等距同速指针
class Solution {
public int kthToLast(ListNode head, int k) { //首末重合
ListNode pioneer=head;
while(k-->0)pioneer=pioneer.next;
while(pioneer!=null){
pioneer=pioneer.next;
head=head.next;
}
return head.val;
}
}
注:有人把这种方法也叫做快慢指针,我认为是不妥的~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。