返回链表中倒数第k个节点

2022-10-26 14:42:52 浏览数 (1)

思路: 定义fast 和 slow ,先让fast走k-1步,然后再让slow和fast同时走1步,最后得到的slow就是所求的值

代码示例

代码语言:javascript复制
lass ListNode {
    public int val;
    public ListNode next;
    public ListNode(int val){
        this.val = val;
        this.next = null;
    }
}

public class TestDemo1025_1 {
    public ListNode head;
    public ListNode findLastK(int k){
        if (k <= 0 ){
            System.out.println("不合法");
            return null;
        }
        ListNode fast = this.head;
        ListNode slow = this.head;
        while (k-1 != 0){
            if (fast.next != null){
                fast = fast.next;
                k--;
            }else {
                System.out.println("没有这个节点");
                return null;
            }
        }
        while (fast.next != null){
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}

0 人点赞