AcWing 33. 双指针-Java
原题链接
简单
作者:
zlnnjit
,
2021-03-27 13:39:07
,
所有人可见
,
阅读 531
双指针
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode findKthToTail(ListNode pListHead, int k) {
if (k == 0 || pListHead == null) return pListHead;
int len = 0;
ListNode cur = pListHead;
while (cur != null) {
cur = cur.next;
len++;
}
if (k > len) return null;
ListNode fast = pListHead, slow = pListHead;
while (k-- > 0) {
fast = fast.next;
}
while(fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}