题目要求:输入一个链表,输出该链表中倒数第k个结点。
思路:
- 取两个指针,第一个先走,到了第k个节点,然后两个指针一起走,当第一个到了末尾时,第二个就到了倒数第k个了。这个思路复杂度最低
- 将节点压入栈中,再弹出第k个
- 翻转链表,取第k个
- 计算链表总节点个数n,再取第n-k个
这里要注意输入k大于链表总长度和小于1的情况
思路1代码:
class Solution:
def FindKthToTail(self, head, k):
# write code here
p1=head
p2=head
i=0
while p1!=None:
if i>=k:
p2=p2.next
p1=p1.next
i+=1
return p2 if i>=k and k>0 else None
思路2代码:
class Solution:
def FindKthToTail(self, head, k):
# write code here
res=[] #用列表来代替栈
while head:
res.append(head)
head=head.next
if k>len(res) or k<1:
return None
return res[-k]