Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91411250
welcome to my blog
Offer surface prove safety questions 22 (java version): the list penultimate node K
Title Description
Input a linked list, the linked list output reciprocal k-th node.
notes
- To robustness determination: the input node is null; k <= 0 are exceptions
the complexity
- Time complexity: O (n)
- Space complexity: O (1)
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
// input check
if(head == null || k<=0)
return null;
//execute
ListNode fast = head;
ListNode slow = head;
// 下面这个循环让fast位于第K个Node上; 非正常退出循环说明链表长度不足K
for(int i = 0; i < k - 1; i++){ // 包括slow在内, 从slow到fast是K个节点; 所以fast得先向前移动K-1步
if(fast.next == null)
return null; // 链表长度不足K
fast = fast.next;
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
Extremely clean code
To grasp that method above, feeling largely reflects careful thinking of when general interview
public ListNode FindKthToTail(ListNode head,int k) {
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;
}