题目描述: 解题思路: 因为题目给出的是倒数第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
);
}
}
执行结果:
转载请注明原文地址:https://blackberry.8miu.com/read-39323.html