# 1.5python找出单链表中的倒数第k个元素

1. 顺序遍历两遍法

2. 快慢指针法

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2020/1/16 19:35
# @Author  : buu
# @Software: PyCharm
# @Blog    ：https://blog.csdn.net/weixin_44321080
class LNode:
def __init__(self, data=None, next=None):
self.data = data
self.next = next

def ConstructList():
"""
构造一个单链表
:return: 链表的头结点
"""
i = 1
tmp = None
while i < 8:
tmp = LNode(i)
cur.next = tmp
cur = tmp
i += 1

"""
顺序打印单链表结点的数据
:return:
"""
print('raw list:', end=' ')
while cur is not None:
print(cur.data, end=' ')
cur = cur.next
print()

"""
找出链表倒数第k个结点
:return: 倒数第k个结点
"""
i = 0
while i < k and fast is not None:  # 快指针先走k步
fast = fast.next
i += 1
if i < k:  # 未走k步，快指针已到链表尾部
return None
while fast is not None:
fast = fast.next
slow = slow.next
return slow

if __name__ == '__main__':
result = None
if result != None:
print('last3 is:', result.data)


1. 首先找到链表倒数第k+1个结点slow和尾结点fast(如下图所示)；
2. 把链表断开为两个子链表，其中，后半部分链表结点的个数为k；
3. 使原链表的尾结点指向链表的第一个结点(而非头结点)；
4. 使链表的头结点指向原链表倒数第k个结点；

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2020/1/16 20:23
# @Author  : buu
# @Software: PyCharm
# @Blog    ：https://blog.csdn.net/weixin_44321080
class LNode:
def __init__(self, data=None, next=None):
self.data = data
self.next = next

def ConstructList():
"""
构造一个单链表
:return: 链表的头结点
"""
i = 1
tmp = None
while i < 8:
tmp = LNode(i)
cur.next = tmp
cur = tmp
i += 1

"""
顺序打印单链表结点的数据
:return:
"""
while cur is not None:
print(cur.data, end=' ')
cur = cur.next
print()

"""
把链表右旋k个位置
:param k: k个位置
:return:
"""
return
tmp = LNode()
i = 0
while i < k and fast is not None:
fast = fast.next
i += 1
if i < k:
return None
while fast.next != None:  # FindLastK.py中是 fast != None
slow = slow.next  # 循环结束后，slow指向倒数第k+1个元素；
fast = fast.next  # fast指向最后一个元素
tmp = slow.next  # tmp 指向包含后k个元素链表的首结点
slow.next = None

if __name__ == '__main__':
print('before rotation:', end=' ')
print('after  rotation:', end=' ')