快慢指针
快走的k步数真好就是:这个链表的倒数第k个节点。。。
JAVA实现
package swordPointingToTheOffer;
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class TwentyTwo {
public static ListNode getKthFromEnd(ListNode head, int k) {
//快慢指针,慢k个节点
if(head==null){
return null;
}
ListNode fast = head;
ListNode slow = head;
for (int i =0;i<k;i++){
//异常退出条件
if(fast==null){
return null;
}
fast = fast.next;
}
//直到fast移动到最末,就结束
while (fast!=null){
fast=fast.next;
slow=slow.next;
}
return slow;
}
public static void main(String[] args) {
ListNode listNode1 = new ListNode(1);
ListNode listNode2 = new ListNode(2);
ListNode listNode3 = new ListNode(3);
ListNode listNode4 = new ListNode(4);
ListNode listNode5 = new ListNode(5);
listNode1.next = listNode2;
listNode2.next = listNode3;
listNode3.next = listNode4;
listNode4.next = listNode5;
ListNode tem = getKthFromEnd(listNode1,2);
while (tem!=null){
System.out.println(tem.val);
tem = tem.next;
}
}
}