劍指 offer 鏈表倒數的第k個數

快慢指針

快指針線遍歷到第k-1個數,然後慢指針在從頭開始遍歷,這樣快慢指針有k-1個間隔,當快指針到鏈表末尾時,慢指針指的數就是倒數第k個數。

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
            if(head==null||k==0){
                return null;
            }
            ListNode pHead=head;
            for(int i=0;i<k-1;i++){
                if(pHead.next!=null){
                    pHead=pHead.next;
                }
                else{
                    return null;
                }
            }
            ListNode pSlow=head;
            while(pHead.next!=null){
                pHead=pHead.next;
                pSlow=pSlow.next;
            }
            return pSlow;
    }
}

發佈了104 篇原創文章 · 獲贊 44 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章