"Leetcode" "Python" Linked List Cycle

Source: Internet
Author: User

Given A linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

Idea: The stupid way is to each node and then open up a property store whether or not to visit, so walk through it can know whether there is a ring. But in order not to add extra space. Ability to set two pointers. One step at a time, and one step at a time, assuming that there is a ring two pointers will meet again. Conversely, it does not.

# Definition for singly-linked list.# class listnode:#     def __init__ (self, x): #         self.val = x#         Self.next = Nonec Lass Solution:    # @param head, a listnode    # @return a Boolea    def hascycle (self, head):        if head is none:
    return False        p1 = head        P2 = head while        True:            If p1.next are not None:                p1=p1.next.next                p2= P2.next                If P1 is None or P2 is none:                    return False                elif P1 = = P2:                    return True            else:                return Fa LSE        return False

"Leetcode" "Python" Linked List Cycle

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.