标签:长度 ota kth lse else section 输入 ndk his
输入一个链表,输出该链表中倒数第k个结点。
假设原链表有n个结点,倒数第k个结点就是n-k+1个结点,那么这里可以设置两个结点,一个结点先走k-1步,是第k个结点,然后两个结点一起走,第一个结点再走n-k步就到达末尾,此时第二个结点也走了n-k步,到达了n-k+1个结点,就是所求的值。 这里有几点需要注意,就是k的范围,若k<=0那么直接返回null,若链表为空那也返回null,若链表长度小于k一样返回null
  public class ListNode {
    int val;
    ListNode next = null;
    ListNode(int val) {
      this.val = val;
    }
  }
  public ListNode FindKthToTail(ListNode head, int k) {
    if (head == null || k <= 0) {
      return null;
    }
    ListNode ans = head;
    for (int i = 0; i < k - 1; i++) {
      if (head.next != null) {
        head = head.next;
      } else {
        return null;
      }
    }
    while (head.next != null) {
      head = head.next;
      ans = ans.next;
    }
    return ans;
  }
标签:长度 ota kth lse else section 输入 ndk his
原文地址:https://www.cnblogs.com/blogxjc/p/12376252.html