[Sword refers to offer] The second-to-last node in the linked list

Title description
Input a linked list and output the kth node from the bottom of the linked list.
Example 1

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

The idea of ​​solving the problem
is the length of the reciprocal + positive number in the linked list is equal to the total length of the linked list, so you can set two pointers slow and fast, one takes k steps first, and the remaining number of steps to go to the end of the linked list is the last kth A node, the number of steps that need to be taken from the beginning.

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;
    }
}

Guess you like

Origin blog.csdn.net/qq_45621376/article/details/114554334