python查找链表倒数第K个元素
class Node:
def __init__(self,data=None):
self.data=data
self.next=None
class ListNode:
def __init__(self):
self.head=Node()
def append(self,num):
node=Node(num)
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=node
def print(self):
cur=self.head
while cur.next!=None:
print('data:',cur.data)
cur=cur.next
print('end:',cur.data)
def find_key(self,K):
head=self.head
slow=head.next
fast=head.next
for i in range(K):
fast=fast.next
while fast!=None:
slow=slow.next
fast=fast.next
print(f'倒数第{K}个元素值为{slow.data}')
if __name__ == '__main__':
list=ListNode()
for i in range(1,10):
list.append(i)
list.print()
list.find_key(3)
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
喜欢就支持一下吧