题目描述:
找出单链表中的倒数第k个元素,例如给定单链表:1->2->3->4->5->6->7,则单链表的倒数第k=3个元素为5。
# 如何找出单链表中的倒数第K个元素
# 定义链表
class LNode():
def __init__(self):
self.data = None # 定义数据域
self.next = None # 定义指针域
# 构造一个单链表
def ConstructList():
head = LNode()
temp = head
i = 1
# 构造单链表
while i<=7:
cur = LNode()
cur.data = i
temp.next = cur
temp = cur
i += 1
temp = head.next
# 输出构造的单链表
while temp!=None:
#print(temp.data)
temp = temp.next
return head
# 查找单链表的倒数第K个元素
def FindElement(head, k):
if head==None or head.next==None:
return head
# 定义慢指针
slow = head.next
# 定义快指针
fast = head.next
i = 0
while i