面试02.02.返回倒数第k个节点(Java)

    科技2025-06-19  13

    题目描述: 解题思路:     因为题目给出的是倒数第k个节点,所以我们先要遍历ListNode,算出所有层数count。然后count - k,就是这个节点顺数的层数。然后我们再遍历ListNode,每遍历一次层数减1,层数为0的时候就是要求的当前层,返回此层的数据即可。

    代码实现:

    class Solution { int count = 0; public int kthToLast(ListNode head, int k) { bianli(head); return bianli2(head, count - k); } public void bianli(ListNode head){ if(head == null) return ; count++; bianli(head.next); } public int bianli2(ListNode head, int k){ if(k == 0) return head.val; return bianli2(head.next, --k); } }

    执行结果:

    Processed: 0.011, SQL: 8