题目描述:
输入一个链表,输出该链表中倒数第k个结点。
解题思路:
注意代码的鲁棒性,要充分考虑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
array = []
if head == None or k<=0:
return None
index1 = head
index2 = head
count = 0
#判断k是不是超过了链表的总长度
#--------------------------------
while index2!=None and count < k:
index2 = index2.next
count = count + 1
if count < k :
return None
#--------------------------------
while index2!=None:
index1 = index1.next
index2 = index2.next
return index1
网友评论