python面试之查找链表倒数第K个元素

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
喜欢就支持一下吧
点赞0
分享
评论 抢沙发
程序员吾非同的头像-程序员吾非同

昵称

取消
昵称表情代码图片