1. 程式人生 > >找出鏈表中倒數第K個結點

找出鏈表中倒數第K個結點

span 節點 i++ code ext else head count fas

思路:兩個指針,也是快指針和慢指針,先讓快指針走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; }

找出鏈表中倒數第K個結點