【剑指offer】链表中倒数第二个结点

题目描述
输入一个链表,输出该链表中倒数第k个结点。
示例1

输入
{
    
    1,2,3,4,5},1
返回值
{
    
    5}

解题思路
在链表中倒数的+顺数的长度等于链表总长度,所以可以设置两个指针slow和fast,一个先走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) {
    
    
        // write code here
        if(pHead == null) return null;
        ListNode fast = pHead;
        ListNode slow = pHead;
        int count = 0;
        while(count < k && fast != null) {
    
    
            count++;
            fast = fast.next;
        }
        if(count < k) return null;
        while(fast != null){
    
    
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45621376/article/details/114554334