您的位置:首页 > 其它

判断链表 有环

2015-07-21 20:39 423 查看
第一种解法,记录每一出现的元素
/**
* 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) {

map<ListNode *,bool>m;
while(head){
if(m.count(head)) return true;
else m.insert(pair<ListNode *,bool>(head,true));
head = head->next;
}
return false;
}
};


第二种解法,把每一个出现过的元素值改成一个不可能出现的值,eg:99999

class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL) return false;
ListNode *temp=head;
ListNode *temp1;
int val =temp->val;
ListNode x(99999);
ListNode *x_p = &x;
while((temp->next!=x_p) && ((temp->next!=NULL)))
{
temp1 =  temp;
temp =temp->next;
temp1->next = x_p;
}
if(temp->next == x_p)
return true;
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: