首页 > 其他 > 详细

判断链表 有环

时间:2015-07-21 21:48:58      阅读:145      评论:0      收藏:0      [点我收藏+]
第一种解法,记录每一出现的元素
/*
* * 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;
    }

 

判断链表 有环

原文:http://www.cnblogs.com/julie-yang/p/4665567.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!