14.链表中倒数第k个结点
问题:
输入一个链表,输出该链表中倒数第k个结点。
解决:
思想:
Python 设置两个指针,p1,p2,先让p2走k-1步,然后再一起走,直到p2为最后一个 时,p1即为倒数第k个节点
python代码
# -*- 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
if head==None or k<=0:
return None
current=head
while k>0:
if current!=None:
current=current.next
k-=1
else:
return None
backup=head
while(current!=None):
current=current.next
backup=backup.next
return backup