链表中倒数第k个结点python
思路1:
两遍循环,第一遍得到链表的总数n,得到倒数第k个节点的下标n-k;第二遍遍历到第n-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
if head is None or k<=0:
return None
count = 0
p = head
while p:
p = p.next
count += 1
if k > count:
return None
for i in range(count-k):
head = head.next
return head
思路2:只遍历一次链表的方法呢?本题其实是很典型的快慢双指针问题,快指针先走k步,然后快慢指针再同时往前走,当快指针走到尽头时,慢指针刚好在倒数第k个节点的位置上。这样只需要遍历一次链表即可。唯一需要注意的问题是小心参数k值大于链表长度。
https://blog.csdn.net/qq_20141867/article/details/80919029
# -*- 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 is None or k <= 0:
return None
pre = post = head
for i in range(k):
if pre:
pre = pre.next
else:
return None
while pre:
pre = pre.next
post = post.next
return post