这道题做法有很多种,首先讲一下像我这种脑子不是很好使的直白的做法。
当然是先循环求出长度,再循环找到倒数第k个节点,即整数的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 length = 0;
ListNode temp = new ListNode(0);
while(head.next!=null){
}
while(head!=null){
if(length == k){
return head;
}
length--;
head = head.next;
}
return null;
}
}
然后讲一下比较聪明的做法:
设置两个指针,一个快指针,一个慢指针。快指针先走k步,然后慢指针再开始走。当快指针到达终点时,慢指针的位置就是倒数第k个节点。其实很好理解。他们一起走的长度是n-k。即慢指针走了n-k的长度。还剩下k的长度。即是倒数第k个节点。
/*
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 length = 0;
ListNode fast = head;
ListNode slow = head;
while(fast!=null){
if(k > 0){
k--;
}else{
slow = slow.next;
}
fast = fast.next;
}
if(k!=0)
return null;
return slow;
}
}
还有一种做法其实也是比较常见的。前提是递归思想对于你已经根深蒂固。写递归的时候碰到一个奇怪的问题,cnt变量不要设置成static的。不然答案会少一个节点。比如5{1,2,3,4,5},答案会是{2,3,4,5}。至于为什么不能是静态我也说不太明白,估计和初始化顺序有关系。有大神看到,希望给出仔细的回答。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
int cnt = 0;
public ListNode FindKthToTail(ListNode head,int k) {
if(null == head){
return null;
}
ListNode temp = FindKthToTail(head.next,k);
if(temp!=null){
return temp;
}
cnt++;
if(cnt == k){
return head;
}else{
return null;
}
}
}