1.5寻找倒数第k个元素
寻找倒数第k个元素
方法一:
将单链表逆置,变换成寻找正数第k个元素
方法二:
快慢指针法,快指针比慢指针快k个节点,当快指针到达尾节点时,慢指针为倒数第k个节点
方法三:
顺序遍历两次链表法,第一次遍历求出链表长度n,将寻找倒数第k个元素转换成寻找正数第n-k个元素
代码实现方法二:
# -*-coding:utf-8-*-
"""
@Author : 图南
@Software: PyCharm
@Time : 2019/9/5 18:03
"""
# 方法一:将单链表逆置,变换成寻找正数第k个元素
# 方法二:快慢指针法,快指针比慢指针快k个节点,当快指针到达尾节点时,慢指针为倒数第k个节点
# 方法三:顺序遍历两次链表法,第一次遍历求出链表长度n,将寻找倒数第k个元素转换成寻找正数第n-k个元素
# 本代码实现方法二
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def con_link(n):
head = Node()
cur = head
for i in range(1, n+1):
node = Node(i)
cur.next = node
cur = node
return head
def print_link(head):
cur = head.next
while cur:
print(cur.data, end=' ')
cur = cur.next
print()
def getLastK(head, k):
fast = head
slow = head
while k:
fast = fast.next
k -= 1
while fast:
fast = fast.next
slow = slow.next
return slow.data
if __name__ == '__main__':
head = con_link(7)
print_link(head)
print(getLastK(head, 1))
运行截图:
![](https://img2018.cnblogs.com/blog/1417701/201909/1417701-20190906150708351-1826275837.jpg)
![](https://img2018.cnblogs.com/blog/1417701/201909/1417701-20190906152227407-257281287.jpg)