1. 程式人生 > >劍指Offer | 連結串列中倒數第k個結點

劍指Offer | 連結串列中倒數第k個結點

做了個劍指Offer的題目目錄,連結如下:
https://blog.csdn.net/mengmengdastyle/article/details/80317246
一、題目
輸入一個連結串列,輸出該連結串列中倒數第k個結點。
二、思路
(1) 先寫出步驟,將各種情況考慮到
//1.為空
//2.拿到總長度
//3.大於總長度時,返回空
//4.小於總長度時,總數-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) { //1.為空 if(head==null){ return null; } //2.拿到總長度 int count = 0; ListNode n = head; while(n != null){ n = n.next; count++; } //3.大於總長度時,返回空
if(count<k){ return null; } //4.小於總長度時,總數-k int mm = 1; ListNode tem = head; for (int i = 0; i < count - k; i++) { tem = tem.next; } return tem; } }