Linked List Cycle 判断链表是否有环

来源:互联网 发布:科蓝软件 编辑:程序博客网 时间:2024/05/20 07:19

Linked List Cycle

 

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

Follow up:
Can you solve it without using extra space?

/** * 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) {                if(head==NULL)             return false;        ListNode *slow,*fast;        slow=head;        fast=head;        while(fast!=NULL&&fast->next!=NULL)        {            slow=slow->next;            fast=fast->next->next;            if(slow==fast)                return true;        }        return false;    }};

0 0
原创粉丝点击