python实现链表中倒数第k个结点
题目描述
输入一个链表,输出该链表中倒数第k个结点
第一种实现:
# -*- 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 l = [] while head != None: l.append(head) head = head.next if k > len(l) or k < 1: return return l[-k]
第二种实现:
# -*- 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 if head == None or k == 0: return None pAhead = head pBehind = None for i in range(0,k-1): if pAhead.next != None: pAhead = pAhead.next else: return None pBehind = head while pAhead.next != None: pAhead = pAhead.next pBehind = pBehind.next return pBehind