鏈表中倒數第k個節點

 AcWing打卡活動

《劍指Offer》打卡活動 

週二第十題   鏈表中倒數第k個節點

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 * 
 * 思路
 * 設列表總結點數爲n, 則n-(k-1)爲該列表的倒數第k個節點
 * 如:n = 10, k = 2, 則 10 - (2 - 1) = 9, 爲倒數第k(k=2)個節點
 * 如何得到n,使用for循環計數器i
 */
class Solution {
    public ListNode findKthToTail(ListNode pListHead, int k) {
        if(pListHead == null || k <= 0) {
            return null;
        }
        ListNode head = pListHead;
        // 使用計數器i,可得出n
        for(int i = 0; i < k - 1; i++) {
            // 如果節點數小於k,則返回null
            if(head.next == null) {
                return null;
            }
            head = head.next;
        }
        // 倒數第k個節點開始從頭節點動
        ListNode behind = pListHead;
        while(head.next != null) {
            head = head.next;
            behind = behind.next;
        }
        return behind;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章