Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does python judge whether a linked list has a ring?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

In this article, the editor introduces in detail "python how to judge whether the linked list has a ring", the content is detailed, the steps are clear, and the details are handled properly. I hope that this "python how to judge whether the linked list has a ring" article can help you solve your doubts, following the editor's ideas slowly in depth, let's learn new knowledge.

What does it mean that a linked list has a ring?

Before judging whether there is a ring, you need to know what is a ring in a linked list.

The linked list shown below consists of five nodes, and the number in the box represents the number and can also be understood as the address of the node. Note that the data fields that distinguish between address values and linked lists are completely different:

Node 0 points to node 3, and node 10 points to node 3, so node 3 is the entrance to the ring, forming a ring like this:

If you traverse a linked list like this:

# head is the head of the linked list

While head:

Print (head.data)

Head = head.next

The program will enter an endless loop and run endlessly in the ring.

Therefore, it is a very meaningful topic to study how to judge whether the linked list has rings or not, and it is also often tested in interviews.

2 how to judge whether the linked list has rings or not

Through the hash method, the code is easier to understand:

Class Solution (object):

Def hasCycle (self, head):

S = set ()

Tmp = head

While tmp:

If tmp in s:

Return True

S.add (tmp)

Tmp = tmp.next

Return False read here, this article "python how to determine whether the linked list has rings" article has been introduced, want to master the knowledge of this article still need to practice and use in order to understand, if you want to know more related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report