链表中倒数第k个结点 python

输入一个链表,输出该链表中倒数第k个结点。

使用双指针,注意判断列表是否为空,k不为0,k要小于链表长度。

class ListNode:
	def __init__(self, x):
		self.val = x
		self.next = None

calss Soultion:
	def FindKthTotail(self, head, k):
		if head == None or k == 0:
			if head == None or k == 0:
				return None
		pA = head
		pB = head
		for i in range(k-1):
			if pA.next != None:
				pA = pA.next
			else:
				return None
		while pA != None:
			pA = pA.next
			pB = pB.next
		return pB

你可能感兴趣的:(刷题)