题目

输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。

链接:https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof

思路

快慢指针。快指针先走k步,慢指针再走。当快指针走到最后,慢指针所指的位置就是倒数第k个节点。

特别注意:

  • 链表为空
  • 总结点少于k
  • 输入k为0

代码

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
  8. # 快慢指针
  9. fast_ptr = head
  10. slow_ptr = head
  11. i = 0
  12. while fast_ptr is not None:
  13. if i < k:
  14. # fast_ptr = fast_ptr.next
  15. i += 1
  16. else:
  17. # fast_ptr = fast_ptr.next
  18. slow_ptr = slow_ptr.next
  19. fast_ptr = fast_ptr.next
  20. return slow_ptr
  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
  8. # 快慢指针
  9. # fast_ptr = head
  10. if head.next is None or k == 0:
  11. return head
  12. slow_ptr = head
  13. i = 0
  14. while head is not None:
  15. if i < k:
  16. # fast_ptr = fast_ptr.next
  17. i += 1
  18. else:
  19. # fast_ptr = fast_ptr.next
  20. slow_ptr = slow_ptr.next
  21. head = head.next
  22. return slow_ptr if i == k else None