Skip to content

Latest commit

 

History

History
53 lines (40 loc) · 1005 Bytes

20200904.md

File metadata and controls

53 lines (40 loc) · 1005 Bytes

Algorithm

剑指offer-链表中倒数第k个节点

Description

输入一个链表,输出该链表中倒数第k个结点。

Solution

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
      ListNode fast = head;
      ListNode slow = head;
      int a = k;
      int count = 0;
      while(fast!=null){
        fast = fast.next;
        count ++;
        if(k<1){
            slow = slow.next;
        }
        k--;
      }
      if(count < a){
          return null;
      }
      return slow;
    }
}

Discuss

快指针走一步,慢指针先不走,等到快指针走了K步之后,慢指针开始走,如果所有的步数之和大于K,说明慢指针

Review

Tip

Share