输入一个链表,输出该链表中倒数第k个结点。
思路
遍历链表,将i移到k位,接下来j和i一起移动,直到i到达最后,j位就是倒数第k个节点
Java
/*
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 || k ==0 ){
return null;
}
int i = 0;
ListNode fast = head;
while (i < k) {
i++;
if (fast == null) {
return null;
}
fast = fast.next;
}
while (fast != null) {
head = head.next;
fast = fast.next;
}
return head;
}
}
网友评论