https://blog.csdn.net/slibra_L/article/details/78176540
题目:输入一个链表,输出该链表中倒数第k个结点。
基本思路:遍历一次链表获得链表长度,再次遍历链表,至n-k+1出输出
# -*- 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
p = head
n = 1
while p.next != None:
p = p.next
n = n+1
if k > n:
return None
for i in range(n-k):
head = head.next
return head
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
进阶思路:设置2个指针,第一个指针走K步之后,第二个指针开始从头走,这样两个指针之间始终相隔K,当指针2走到链表结尾时,指针1的位置即倒数K个节点
思路推广:寻找中间节点, 两个指针一起, 第一个指针每次走两步, 第二个指针每次走一步, 快指针指到尾部, 慢指针正好指到中间
class Solution:
def FindKthToTail(self, head, k):
# write code here
if head == None or k <= 0:
return None
p1 = head
p2 = head
for i in range(k-1):
if p1.next == None:
return None
p1 = p1.next
while p1.next != None:
p1 = p1.next
p2 = p2.next
return p2