题目
输入一个链表,输出该链表中倒数第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
代码
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution:def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:# 快慢指针fast_ptr = headslow_ptr = headi = 0while fast_ptr is not None:if i < k:# fast_ptr = fast_ptr.nexti += 1else:# fast_ptr = fast_ptr.nextslow_ptr = slow_ptr.nextfast_ptr = fast_ptr.nextreturn slow_ptr
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution:def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:# 快慢指针# fast_ptr = headif head.next is None or k == 0:return headslow_ptr = headi = 0while head is not None:if i < k:# fast_ptr = fast_ptr.nexti += 1else:# fast_ptr = fast_ptr.nextslow_ptr = slow_ptr.nexthead = head.nextreturn slow_ptr if i == k else None
