【每日一道算法题】链表中倒数第K个节点

107 阅读1分钟

输入一个链表,输出该链表中倒数第k个结点。如果该链表长度小于k,请返回空。

解法:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode FindKthToTail (ListNode pHead, int k) {
        if(pHead==null) return pHead;
        ListNode first =pHead;
        ListNode second =pHead;
        for(int i=0;i<k;i++){
            if(first==null) return null;
            first=first.next;
        }
        while(first!=null){
            first=first.next;
            second=second.next;
        }
        return first;
    }
}