判断链表 有环

第一种解法,记录每一出现的元素
/*
* * 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;
    }

 

posted @ 2015-07-21 20:39  *桔子*  阅读(166)  评论(0编辑  收藏  举报