推荐方法链接:https://www.nowcoder.com/questionTerminal/529d3ae5a407492994ad2a246518148a?f=discussion
> public ListNode FindKthToTail(ListNode head,int k) { //5,{1,2,3,4,5}
> ListNode p, q;
> p = q = head;
> int i = 0;
> for (; p != null; i++) {
> if (i >= k)
> q = q.next;
> p = p.next;
> }
> return i < k ? null : q;
> }以下为自行写的 **
**Java 题解,笨方法。
先进行判断节点总的数量,然后再从前向后找第 n-k+1 个节点。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
int totalNum = 0;
if(head != null){
totalNum++;
}else{
return null;
}
// 计算总的节点数量
ListNode currentNode = head.next;
while(currentNode != null){
totalNum++;
currentNode = currentNode.next;
}
if(totalNum < k){
//throw new RuntimeException("k的值超过了链表长度");
return null;
}
// 倒数第k个为正数第totalNum-k+1个
ListNode resultNode = head;
for(int i=1; i<=totalNum-k; i++){
resultNode = resultNode.next;
}
return resultNode;
}
}
京公网安备 11010502036488号