'''输入一个链表,输出该链表中倒数第k个结点'''
#常规解法,考虑了代码的鲁棒性,考虑了空指针,K为0,K大于链表的长度
class Solution:
def FindKthToTail(self, head, k):
# write code here
if (head == None or k == 0):
return None
nodeFir = head
nodeSco = head
for i in range(1,k):
if (nodeFir.next != None):
nodeFir = nodeFir.next
else:
return None
while(nodeFir.next != None):
nodeFir = nodeFir.next
nodeSco = nodeSco.next
return nodeSco
#用栈的特性来解决这个问题,先压入栈,再取出K个值便是倒数第K个值
class Solution:
def FindKthToTail(self, head, k):
# write code here
if (head == None or k == 0):
return None
count = 0
stack = []
while (head != None):
stack.append(head)
head = head.next
count += 1
if (count < k):
return None
for i in range(0,k):
kNode = stack.pop()
return kNode
输入一个链表,输出该链表中倒数第k个结点。
最新推荐文章于 2020-11-23 20:22:31 发布