输入一个链表,输出该链表中倒数第k个结点。
利用栈先进后出的特性,先遍历链表,将节点依次压入栈中,然后在从栈里pop 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
node= None
stack = []
temp = head
while temp:
stack.append(temp)
temp = temp.next
if len(stack)>=k:
for i in range(k): # pop k 次就是倒数第k个节点
node = stack.pop()
return node
else:
return None
构建两个相距为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
fast = slow = head
for i in range(k): # 快指针先走k步
if fast:
fast = fast.next
else:
return None # 注意链表的长度可能小于k,这时就应该返回None。
while fast: # 当快指针走了k步之后,快慢指针一块走,直到fast走到链表尾部。
fast = fast.next
slow = slow.next
return slow