思路:
1、迭代,二指针,快的先走n步,然后一起走,当fast走到最后,slow就是结果
2、递归,到达链表末尾返回一个0计数器,当计数器等于k时就是第k个
迭代
ListNode nthToLast(ListNode head, int n) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && n > 0) {
fast=fast.next;
n--;
}
while (fast != null) {//不是if
fast = fast.next;
slow = slow.next;
}
return slow;
}
递归
public static int nthtolast(ListNode head,int k) {
if (head == null) {
return 0;
}
int i = nthtolast(head.next,k) + 1;
if (i == k) {
System.out.println(head.val);
}
return i;
}
直接返回节点的值
public static ListNode nthtolast(ListNode head,int k,IntWrapper i) {
if (head == null) {
return null;
}
ListNode node= nthtolast(head.next,k,i);
i.value = i.value+1;
if (i.value == k) {
return head;
}
return node;
}
class IntWrapper{
public int value = 0;
}