【剑指Offer】面试题22:链表中倒数第k个节点

本文介绍如何使用栈和快慢指针的方法解决链表中查找倒数第k个节点的问题。通过实例展示了两种方法的实现过程,并分析了它们的时间和空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import org.omg.CORBA.NO_IMPLEMENT;

import java.util.Stack;

/**
 * 面试题22:链表中的倒数第K个节点
 * 题目:输入一个链表,输出该链表中倒数第k个结点。
 * 输入:{1,2,3,4,5},1
 * 输出:{5}
 * @author
 * @create 2021-03-23 10:38
 */
public class Solution22 {
    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node6 = new Node(6);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        Node res = findKthToTailSecond(node1,2);
        System.out.println(res);


    }

    /**
     * 方法一:栈,时间复杂度O(n),空间复杂度O(n)
     * @param pHead
     * @param k
     * @return
     */
    public static Node findKthToTail(Node pHead, int k){
        if (pHead == null || k < 1){
            return null;
        }
        Stack<Node> stack = new Stack<>();
        Node head = pHead;
        Node res = null;
        while (head != null){
            stack.push(head);
            head = head.next;
        }
        int size = stack.size();
         if (k > size){
            return null;
        }
        for (int i = 0 ; i< size;i++){
            if (i == k - 1){
                res = stack.pop();
//                res.next = null;
                break;
            }
            stack.pop();
        }
        return res;
    }

    /**
     * 方法二:快慢指针,时间复杂度O(n),空间复杂度O(1)
     * @param pHead
     * @param k
     * @return
     */
    public static Node findKthToTailSecond(Node pHead, int k){
        if (pHead == null || k < 1){
            return null;
        }
        Node fast = pHead;
        for (int i = 0; i<k;i++){
            if (fast != null){
                fast = fast.next;
            }else {
                return null;
            }
        }
        Node slow = pHead;
        while (fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}

class Node{
    int val;
    Node next = null;
    public Node(int val){
        this.val = val;
    }

    @Override
    public String toString() {
        return "Node{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值