python面试之判断链表是否有环

判断链表是否有环

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

    @property
    def lastNode(self):
        cur=self.head
        while cur.next!=None:
            cur=cur.next
        return cur

    def print(self):
        cur=self.head
        while cur.next!=None:
            print('data:',cur.data)
            cur=cur.next
        print('end:',cur.data)

    def judge_circle(self):
        slow=self.head.next
        fast=self.head.next
        while fast!=None and fast.next!=None:
            slow=slow.next
            fast=fast.next.next
            if slow==fast:
                print('链表有环')
                return
        print('链表无环')

if __name__ == '__main__':
    list=ListNode()
    for i in range(1,10):
        list.append(i)
    list.lastNode.next=list.head.next.next
    list.judge_circle()
© 版权声明
THE END
喜欢就支持一下吧
点赞0
分享
评论 抢沙发
程序员吾非同的头像-程序员知识精选

昵称

取消
昵称表情代码图片