Leetcode Linked List Cycle

Source: Internet
Author: User

Leetcode problem Solving linked List cycle original problem

Determine if there is a link in a list, can you complete it without applying for additional space?

Note the point:

    • No

Example:

Input:

1->2->3  |  |  5<-4

Output: True

Thinking of solving problems

Continuous traversal along the linked list indicates that the linked list does not exist if a null node is encountered. But if there is a loop, such a traversal will go into the dead loop. Forward on the ring will continue to circle around, we let two different speed of the pointer around the ring forward, then sooner or later the speed of the faster that will catch up slow, so if the speed of catching up with slow, then the list of the existence of the ring, the cycle of termination.

AC Source
# Definition for singly-linked list. class listnode(object):     def __init__(self, x):Self.val = x Self.next =None class solution(object):     def hascycle(self, head):        "" : Type Head:ListNode:rtype:bool "" "Slow = Fast = Head whileFast andFast.next:slow = Slow.next Fast = Fast.next.nextifslow = = Fast:return True        return Falseif__name__ = ="__main__":None

Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.

Leetcode Linked List Cycle

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.