当前位置: 代码迷 >> 综合 >> 剑指 offer 链表倒数的第k个数
  详细解决方案

剑指 offer 链表倒数的第k个数

热度:0   发布时间:2023-10-26 22:32:43.0

快慢指针

快指针线遍历到第k-1个数,然后慢指针在从头开始遍历,这样快慢指针有k-1个间隔,当快指针到链表末尾时,慢指针指的数就是倒数第k个数。

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
            if(head==null||k==0){
                return null;
            }
            ListNode pHead=head;
            for(int i=0;i<k-1;i++){
                if(pHead.next!=null){
                    pHead=pHead.next;
                }
                else{
                    return null;
                }
            }
            ListNode pSlow=head;
            while(pHead.next!=null){
                pHead=pHead.next;
                pSlow=pSlow.next;
            }
            return pSlow;
    }
}

  相关解决方案