鏈表中倒數第k個結點(java版)

【題目描述】輸入一個鏈表,輸出該鏈表中倒數第k個結點。


【解題思路1】
//1.設置兩個指針,inx1先向後移動k-1步,inx2不動。
//2.然後同時向後移動,inx1到達結尾的時候,inx2剛好爲倒數第k個結點。
//3.注意臨界情況。如輸入鏈表爲空,k<=0,或者鏈表長度小於k等

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(k == 0){
            return null;
        }
        if(head == null){
            return head;
        }
        ListNode inx = head;
        int i = 1;
        while(i < k && inx.next != null){
            inx  = inx.next;
            i++;
        }
        if(i<k){
            return null;
        }
        while(inx.next !=null){
            inx = inx.next;
            head = head.next;
        }
        return head;
    }
}

【解題思路2】
//1. 遍歷鏈表,計算鏈表長度。
//2. 計算倒數第k個結點的正向位置和下標。
//3. 返回該結點。

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head == null)
            return null;
        int count = 0;
        ListNode temp = head;
        for (int i = 0; temp != null; temp = temp.next) {
            count++;
        }
        if(k>count)
            return null;
        System.out.println(count);
        //一共有count個,倒數第k個就是正數第count-k+1,下標是count-k
        for(int i = 0;i<count-k;i++){
            head = head.next;
        }
        return head;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章