思路:两个指针,也是快指针和慢指针,先让快指针走k -1步,这时慢指针开始和快指针一起走到尾部。慢指针停止的点就是倒数第k个节点。
public static ListNode findCountDownNode(ListNode head,int k){ if(head == null || k <= 0){ return null; } ListNode fast = head;
for(int i = 0;i < k-1; i++){ if(fast.next != null) { fast = fast.next; } else { return null; } } ListNode slow = head; while(fast.next != null){ fast = fast.next; slow = slow.next; } return slow; }