1. 程式人生 > >劍指Offer-連結串列-(2)

劍指Offer-連結串列-(2)

知識點/資料結構:連結串列

題目描述
輸入一個連結串列,輸出該連結串列中倒數第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 pre= head;
        ListNode  x= head;
        for(int i=0;i<k-1;i++){//這裡是k-1;非常重要!!!
            if(pre.next!=null){
                pre=pre.next;
            }else{
                return null;
            }    
        }
        while(pre.next!=null){
            pre = pre.next;
            x = x.next;
        }
        return x;
    }   
}