首页 > 代码库 > Linked List Cycle

Linked List Cycle

Linked List Cycle

Given 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. 空链表不成环        2. 一个节点自环        3. 一条链表完整成环        */        if(head==NULL)return false;        if(head->next==NULL)return false;        if(head->next==head)return true;         ListNode* y=head->next;        ListNode* x=head->next->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版:

/** * 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&&fast.next!=null){			slow=slow.next;			fast=fast.next.next;			if(slow==fast)				return true;		}		return false;	}}

  

Linked List Cycle