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