JZ-014-链表中倒数第 K 个结点

这篇博客介绍了如何在链表中找到倒数第K个节点的三种方法:通过两次遍历、一次遍历计算长度和双指针法。每种方法都提供了详细的代码实现,并在最后进行了实际测试。文章强调了算法效率和代码清晰性的重要性,适合学习数据结构和算法的程序员阅读。
摘要由CSDN通过智能技术生成
链表中倒数第 K 个结点
题目描述

输入一个链表,输出该链表中倒数第k个结点。

题目链接: 链表中倒数第 K 个结点

代码
/**
 * 标题:链表中倒数第 K 个结点
 * 题目描述
 * 输入一个链表,输出该链表中倒数第k个结点。
 * 题目链接:https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=13&&tqId=11167&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
 */
public class Jz14 {

    public ListNode FindKthToTail11(ListNode head, int k) {
        if (head == null || k < 1) {
            return null;
        }
        ListNode tail = head;
        while (tail != null && k > 0) {
            tail = tail.next;
            k--;
        }
        if (k > 0) {
            return null;
        }
        ListNode result = head;
        while (tail != null) {
            result = result.next;
            tail = tail.next;
        }
        return result;
    }


    public ListNode FindKthToTail(ListNode head, int k) {
        if (head == null || k < 1) {
            return null;
        }
        int cnt = 1;
        ListNode node = head;
        while (node.next != null) {
            node = node.next;
            cnt++;
        }
        if (k > cnt) {
            return null;
        }
        ListNode result = head;
        for (int i = 0; i < cnt - k; i++) {
            result = result.next;
        }
        return result;
    }

    /**
     * 方法二:双指针移动
     * 设链表的长度为 N。设置两个指针 P1 和 P2,先让 P1 移动 K 个节点,则还有 N - K 个节点可以移动。此时让 P1 和 P2 同时移动,
     * 可以知道当 P1 移动到链表结尾时,P2 移动到第 N - K 个节点处,该位置就是倒数第 K 个节点。
     *
     * @param head
     * @param k
     * @return
     */
    public ListNode FindKthToTail2(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        ListNode p1 = head;
        while (p1 != null && k-- > 0) {
            p1 = p1.next;
        }
        if (k > 0) {
            return null;
        }
        ListNode p2 = head;
        while (p1 != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        return p2;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        Jz14 jz14 = new Jz14();
        System.out.println(jz14.FindKthToTail(head, 1).val);
        System.out.println(jz14.FindKthToTail2(head, 1).val);
    }
}

【每日寄语】 你的好运气藏在你的实力里,也藏在你不为人知的努力里,你越努力就越幸运。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

醉舞经阁-半卷书

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值