LeetCode *** 141. Linked List Cycle

来源:互联网 发布:nestopia mac 金手指 编辑:程序博客网 时间:2024/04/29 12:51

题目:

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

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


分析:

利用set比较简单,就不多说了。

同时可以利用一个走的快的与一个走的慢的来进行对比,如果有circle那么走得快的与走得慢始终会相遇。


代码:

利用set:

/** * 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) {                set<ListNode*> record;                while(head){            if(!record.insert(head).second)return true;            head=head->next;        }        return false;    }};


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

0 0