一、题目内容

image.png

二、题解

解法1:

思路

双指针法

  • 倒数第K个节点即为第n-k个节点
  • 定义双指针,一个先走k步,另一再走,当第一个快速节点到达末尾时,慢节点走了n-k,即倒数第k

    代码

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode(int x) { val = x; }
    7. * }
    8. */
    9. class Solution {
    10. public ListNode getKthFromEnd(ListNode head, int k) {
    11. if (head == null) {
    12. return null;
    13. }
    14. ListNode fast = head, slow = head;
    15. for (int i = 0; i < k; i++) {
    16. fast = fast.next;
    17. }
    18. while (fast != null) {
    19. fast = fast.next;
    20. slow = slow.next;
    21. }
    22. return slow;
    23. }
    24. }