您的位置:首页 > 其它

LeetCode *** 141. Linked List Cycle

2016-04-11 21:18 155 查看
题目:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: