题解 | 链表中倒数最后k个结点

链表中倒数最后k个结点

https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9?tpId=13&&tqId=11167&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

解法一、双指针

import java.util.*;

public class Solution {
    public ListNode FindKthToTail (ListNode head, int k) {
        if (head == null || k < 0)
            return null;
        ListNode first = head;
        ListNode last = head;

        for(int i = 0; i < k; i++) { // 第一个指针先向前走k步
            if(first == null) 
                return null; // k超过了链表的长度
            first = first.next;
        }
        while(first != null) { // 两个指针一起走
            first = first.next;
            last = last.next;
        }
        return last;
    }
}

解法二、递归

import java.util.*;

public class Solution {
    public ListNode FindKthToTail (ListNode head, int k) {
        if (head == null || k == 0)
            return null;
        int[] count = new int[1];
        ListNode ret = rec(head, count, k);
        if (count[0] < k)
            return null;
        else 
            return ret;
    }
    // 递归辅助函数
    private ListNode rec(ListNode head, int[] count, int k) {
        if (head == null) {
            count[0] = 0;
            return null;
        }
        ListNode x = rec(head.next, count, k);
        if (k == count[0]) { 
            return x; // 找到了倒数第k个元素
        } else {
            count[0]++;
            return head;
        }
    }
}

解法三、栈

import java.util.*;

public class Solution {
    public ListNode FindKthToTail (ListNode head, int k) {
        if (head == null || k <0)
            return null;
        Stack<ListNode> stack = new Stack<>();
        while (head != null) {
            stack.push(head);
            head = head.next;
        }
        if (k > stack.size())
            return null;
        ListNode ret = null;
        for (int i = 0; i < k; i++) {
            ret = stack.pop();
        }
        return ret;
    }
}
全部评论

相关推荐

02-09 16:14
武汉大学 Java
1.&nbsp;问一下本科经历2.&nbsp;介绍一下你第一个项目3.&nbsp;DDD分层架构比传统的MVC有哪些好处?4.&nbsp;你设计的业务分配的算法介绍一下?5.&nbsp;算法有哪些优化思路?6.&nbsp;动态标签列设计怎么思考的?7.&nbsp;数据量有多大?8.&nbsp;数据量很大的话,数据存储怎么优化?9.&nbsp;如何保证缓存和数据库之间的数据一致性?10.&nbsp;相对于你这个项目用哪种方案?11.&nbsp;项目中遇到的最大的困难是什么?12.&nbsp;介绍一下第二个项目13.&nbsp;模型分析diff的上下文怎么考虑?14.&nbsp;如果diff的关联的上下文很长超过token,你会怎么办?15.&nbsp;你想的这种方案,最后输入给模型的prompt是什么?16.&nbsp;对于大模型的其他组件如RAG和skills有了解吗?17.&nbsp;那你有想过把代码拆分成一些知识库放在rag里面吗?18.&nbsp;有对比过其他模型的分析效果吗?19.&nbsp;golang有了解吗?20.&nbsp;HashMap的底层结构21.&nbsp;为什么要用红黑树?22.&nbsp;红黑树增删的时间复杂度?23.&nbsp;MySQL事务隔离级别24.&nbsp;MVCC实现原理25.&nbsp;手撕算法:lc402&nbsp;移掉k位数字&nbsp;-&gt;&nbsp;没想到单调栈,暴力枚举了QAQ反问面试官之后,感觉我的缺点主要在于项目太过于玩具了,对于高并发什么的思考处于比较浅的地步,还有就是code-review对于call&nbsp;graph还有一些成熟的方案不怎么了解过,相当于纯demo,面过几场才知道QAQ,估计是没啥希望了,继续沉淀了噶人们
查看25道真题和解析
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务