class LNode:
def __init__(self):
self.data = None
self.next = None
def ConstructList():
i = 1
head = LNode()
cur = head
while i<8 :
tmp = LNode()
tmp.data = i
cur.next = tmp
cur = tmp
i += 1
return head
def PrintList(head):
if head is None or head.next is None:
print('Empty!')
return
cur = head.next
while cur is not None:
print(cur.data,end=' ')
cur = cur.next
def FindLastK(head, k):
if head == None or head.next == None :
return head
slow = LNode()
fast = LNode()
fast = head.next
slow = head.next
i = 0
while i<k and fast != None:
fast = fast.next
i += 1
if i<k :
return None
while fast != None:
slow = slow.next
fast = fast.next
return slow
if __name__ == '__main__':
head = ConstructList()
print('链表:',end='')
PrintList(head)
result = FindLastK(head, 3)
if result is not None:
print('\n链表的倒数第3个元素为:'+str(result.data))
Python:如何找出单链表中的倒数第K个元素
最新推荐文章于 2021-11-22 00:39:56 发布