【剑指offer】输出链表倒数第K个元素

时间:2025-04-09 18:36:07
 /*
public class ListNode {
int val;
ListNode next = null; ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head == null) return null;
int length = 0;
ListNode tempNode = head;
ListNode result;
while(tempNode!=null){
length++;
tempNode = tempNode.next;
}
//判断K值是否合法
if(k > length) return null;
tempNode = head;
for(int i=0; i<length; i++){
if(i>=k){
head = head.next;
}
tempNode = tempNode.next;
}
return head;
}
}