【LeetCode】面试题22. 链表中倒数第k个节点

题目:

思路:

快慢指针,快指针先走k步,然后快慢指针一起走。

代码:

Python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getKthFromEnd(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if head is None:
            return None
        end = head
        while k:
            if end is None:
                return None
            end = end.next
            k -= 1
        while end:
            head = head.next
            end = end.next
        return head

相关问题

posted @ 2020-06-01 18:14  一只背影  阅读(83)  评论(0编辑  收藏  举报