【面試題22】鏈表中倒數第k個節點

在這裏插入圖片描述
Python題解

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        if not head or k == 0:
            return None
        ahead = head
        behind = head
        for i in range(k-1):
            if ahead.next != None:
                ahead = ahead.next
            else:
                return None
        while ahead.next != None:
            ahead = ahead.next
            behind = behind.next
        return behind

考點

  • 考查對鏈表的理解;
  • 考查縮寫代碼的魯棒性。魯棒性是解決這道題的關鍵所在,如果寫出的代碼有多處崩潰的潛在風險,那麼很難通過面試。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章