头图

Niuke.com High-Frequency Algorithm Questions Series - BM8 - The last k nodes in the penultimate linked list

Topic description

Description: Input a linked list of length n, set the value of the elements in the linked list as a~i~, and return the kth node from the bottom of the linked list. If the length of the linked list is less than k, return a linked list of length 0.

See the original title: The last k nodes in the BM8 linked list

Solution 1: Double pointer method

First, consider two special cases:

  • If the original linked list is empty, return null directly.
  • If k is not a positive number, return null directly.

Otherwise, use two pointers to solve, the solving process is as follows:

  • First, traverse the linked list and point the fast node to the kth node;
  • If fast is null after traversing, it means that the length of the linked list is less than k, and there is no k-th node from the bottom, and returns null directly;
  • Otherwise, the fast and slow pointers move together until fast moves to the last node. At this time, slow is the kth node from the bottom and returns it.

code

 public class Bm008 {
    /**
     * 链表中倒数最后k个结点
     *
     * @param pHead ListNode类
     * @param k     int整型
     * @return ListNode类
     */
    public static ListNode findKthToTail(ListNode pHead, int k) {
        // 如果原链表为空,直接返回null
        if (pHead == null) {
            return null;
        }
        // 如果k不是正数,直接返回null
        if (k <= 0) {
            return null;
        }
        ListNode fast = pHead;
        // 将fast结点指向第k个结点
        for (int i = 0; i < k - 1 && fast != null; i++) {
            fast = fast.next;
        }
        // 如果fast为null,说明链表长度小于k,不存在倒数第k个结点,直接返回null
        if (fast == null) {
            return null;
        }

        ListNode slow = pHead;
        // 快慢指针一起移动,直到fast移动到最后一个结点,此时,slow即为倒数第k个结点
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }

        return slow;
    }

    public static void main(String[] args) {
        ListNode pHead = ListNode.testCase2();
        System.out.println("原链表为");
        ListNode.print(pHead);
        int k = 2;
        System.out.println("链表中的倒数第" + k + "个结点为:");
        System.out.println(findKthToTail(pHead, k));
    }
}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
Believe in the power of persistence!

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!