返回鏈表中倒數第k個結點

思路:從第一個節點開始遍歷,將當前節點以及當前節點前面K-1個節點存儲在一個容量爲k的數組中,每往後遍歷一個節點,便將數組中所有節點前移一位,並將當前節點存儲在數組的最後一個位置,當遍歷到的節點爲Null時,數組中的第一個節點就是鏈表的倒數第K個節點,代碼如下:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head==null||k<=0){
            return null;
        }
        
        ListNode[] arr = new ListNode[k];      //將當前遍歷到的k個元素按順序存在這個數組裏
        int count = 0;
        while(head!=null){
            if(count<k){                       //數組未滿,依次存儲
                arr[count] = head;
                head = head.next;
                count++; 
            }else{                             //數組已滿,將所有元素前移一位,最後一個元素設置爲當前元素
                for(int i=0;i<k-1;i++){
                    arr[i] = arr[i+1];
                }
                arr[k-1] = head;
                head = head.next;
            }
        }
        if(count<k){           //鏈表沒有K個節點
            return null;
        }
        return arr[0];
    }
}


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