链表中倒数第k个结点

双指针

# 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:
        fir, sec = head, head
        for _ in range(k):
            fir = fir.next
        while fir:
            fir, sec = fir.next, sec.next
        return sec

 

你可能感兴趣的:(Python,LeetCode)