1. 程式人生 > >劍指offer 15. 連結串列中倒數第k個結點

劍指offer 15. 連結串列中倒數第k個結點

原題

輸入一個連結串列,輸出該連結串列中倒數第k個結點。

Reference Answer

解題思路:

對於這種python求解連結串列題,尤其是本題讓返回節點或者值,直接先遍歷玩連結串列轉換到 python 的list中,再進行操作,順風順水。

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

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
res = [] while head: res.append(head) head = head.next if k > len(res) or k < 1: return None else: return res[-k]