剑指 Offer 22. 链表中倒数第k个节点
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ //双指针法,2个指针遍历链表,其中一个先走 k-1 步,然后2个指针一起走,当先走的指针指向空,结束 class Solution { public ListNode getKthFromEnd(ListNode head, int k) { //判空 if(head == null){ return null; } ListNode front = head,later = head; //front 先走 for(int i = 0;i < k;i++){ front = front.next; } //一起走 while(front != null){ front = front.next; later = later.next; } return later; } }