面试题15: 链表中倒数第k个结点
链表中倒数第k个结点
class Solution:
def FindKthToTail(self, head, k):
# write code here
if head == None or k <= 0:
return None
node = head
while k-1 > 0:
if node.next:
node = node.next
k-=1
else:
return None
while node.next != None:
node = node.next
head = head.next
return head
class Solution:
def FindKthToTail(self, head, k):
# write code here
if not head or k <= 0:
return None
node = head
stack = []
while node:
stack.append(node.val)
node = node.next
if k > len(stack):
return None
else:
return stack[-k]
其它
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法