双指针,获取倒数第k个节点的方式就是假设长度为n,需要返回n-k+1那个节点
所以采用双指针,第一个指针先走k步,之后两个指针一起走,当第一个指针走到末尾时,第二个指针刚好走了n-k步
def trainingPlan(self, head, cnt):
"""
:type head: Optional[ListNode]
:type cnt: int
:rtype: Optional[ListNode]
"""
p1 = head
for i in range(cnt):
p1 = p1.next
p2 = head
while p1:
p1 = p1.next
p2 = p2.next
return p2
遍历
class Solution:
def FindKthToTail(self , pHead , k ):
# write code here
if pHead is None or k <= 0:
return None
l=0
p = pHead
while p:
l+=1
p=p.next
if l < k:
return
n=l-k
for i in range(n):
pHead=pHead.next
return pHead