判断链表 有环
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; }
相关文章推荐
- 梅尔频率倒谱系数(MFCC)的提取过程与C++代码实现
- LeetCode 198 House Robber动态规划
- Learning how to learn - Diffuse mode thinking
- 数据库练习题26-45题
- Android 4.0屏蔽式多点触摸
- (好文)Log4j输出格式控制--log4j的PatternLayout参数含义
- poj 1088/2111 滑雪(经典dp/字典序输出)
- iOS初学者
- Linux网络编程之socket文件传输示例
- mysql的远程监控,可以知道mysql的运行情况
- Record-2-3
- 数据库练习题1-25题
- GDAL库三个读取Jpeg2000格式驱动测试
- LA4119 总是整数
- Cloudera Manager 安装时出现socker gaierror[error -2] name or service not know 或者could not contact scm ser
- Record-2-2
- Mathematica 二维符号
- GDAL库三个读取Jpeg2000格式驱动测试
- 控制器转场动画详解
- 服务器采用JSON格式返回数据给安卓客户端