Leetcode OJ 141. 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?

To solve this problem requires a very clever idea, generally we would think of observing whether the linked list has repeated occurrences of the node. However, the complexity of this space is O (n), such as set to store the occurrence of the node, and then see if the next node exists in the set.

A very ingenious solution is to set two pointers, a fast pointer, and a slow pointer. The quick pointer moves two steps at a time, and the slow pointer moves one step at a time. Assuming that two pointers are starting from one node of the ring at the same time, the length of the ring is N. Since the fast pointer is faster than the slow pointer each time, so at most n times the fast pointer moves more than the slow pointer n times, just over the slow pointer One ring, that is, the N word movement after two pointers will definitely meet. And regardless of whether the two pointers are from the same node of the ring, two pointers will meet after M-move, and M<=n (M refers to the number of pointer movements on the ring, because the first half of the list may not be on the ring, so the time of two pointers to the nodes on the ring will be different, the fast pointer will arrive first, Arrives after a slow pointer). The code is as follows:

1  Public classSolution {2      Public Booleanhascycle (ListNode head) {3ListNode slow =head;4ListNode fast =head;5         6          while(slow!=NULL&& fast!=NULL){7slow =Slow.next;8Fast =Fast.next;9             if(fast!=NULL) Fast =Fast.next;Ten             Else return false; One             if(slow = = fast)return true; A         } -         return false; -     } the}

Leetcode OJ 141. 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.