牛客题霸NC69链表中倒数第k个结点Java题解
牛客题霸NC69链表中倒数第k个结点Java题解
方法:快慢指针
解题思路:利用快慢指针,让快指针former先走k步,然后再让快指针former和慢指针latter一起走,这样当快指针指向链表的末尾为null时,慢指针刚好指向链表的倒数第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) { if(head == null || k<=0){ return null; } ListNode former = head; ListNode latter = head; //former先走n步 for(int i=0;i<k;i++){ if(former == null){ //n大于链表长度时 return null; } former = former.next; } //former和latter一起走,当former为null时,latter恰好是倒数第k个节点 while(former!=null){ former = former.next; latter = latter.next; } return latter; } }