Linked List cycle

Source: Internet
Author: User
Linked List cyclegiven a linked list, determine if it has a cycle in it.


C ++

/*** Definition for singly-linked list. * struct listnode {* int val; * listnode * Next; * listnode (int x): Val (x), next (null ){}*}; */class solution {public: bool hascycle (listnode * head) {/* 1. empty linked list is not a ring 2. one node self-ring 3. A linked list is complete into a ring */If (Head = NULL) return false; If (Head-> next = head) return true; listnode * Y = head-> next; listnode * x = head-> next; while (X! = NULL & Y! = NULL) {x = x-> next; If (x = NULL) break; X = x-> next; y = Y-> next; if (x = y) break;} return x = y ;}};

Java version:

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *   * **/  public class Solution {public boolean hasCycle(ListNode head) {ListNode slow=head;ListNode fast=head;while(fast!=null&&!=null){;;if(slow==fast)return true;}return false;}}


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: 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.