142. Linked List Cycle II
2016-05-09 22:52
357 查看
先看141. Linked List Cycle 。
Given a linked list, determine if it has a cycle in it.
判断链表是否有环,用两个快慢指针移动看是否重合即可。
题目142,不仅需要判断是否有环,还需要求环的入口结点。
如果允许使用额外的空间的话。
如果不用额外空间的话,同样需要两个指针。
当快慢指针相遇时,把快指针设置为头结点,
然后快慢指针都每次向前走一步,相遇时即为环的入口。
Given a linked list, determine if it has a cycle in it.
判断链表是否有环,用两个快慢指针移动看是否重合即可。
class Solution { public: bool hasCycle(ListNode *head) { ListNode *first=head,*sec=head; while(first!=NULL&&sec!=NULL&&sec->next!=NULL){ first=first->next; sec=sec->next->next; if(first==sec) return true; } return false; } };
题目142,不仅需要判断是否有环,还需要求环的入口结点。
如果允许使用额外的空间的话。
class Solution { public: ListNode *detectCycle(ListNode *head) { map<ListNode*,bool>; while(head!=NULL){ if(v[head]==true) return head; v[head]=true; head=head->next; } return NULL; } };
如果不用额外空间的话,同样需要两个指针。
当快慢指针相遇时,把快指针设置为头结点,
然后快慢指针都每次向前走一步,相遇时即为环的入口。
class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode *first=head,*sec=head; int fla=1; while(first!=NULL&&sec!=NULL&&sec->next!=NULL){ first=first->next; sec=sec->next->next; if(first==sec){ fla=0; break; } } if(fla) return NULL; sec=head; while(sec!=NULL&&first!=NULL){ if(sec==first)break; sec=sec->next; first=first->next; } return first; } };
相关文章推荐
- Android中的IPC方式(一)—— Bundle、文件共享、Messenger
- 硬件细节
- java学习笔记
- 反编译android中的xml文件
- Codeforces 450D Jzzhu and Cities [heap优化dij]
- Android开发艺术探索(研读笔记)——03-Android中的IPC机制(一)
- JavaScript图片轮播
- Android事件总线分发库EventBus3.0的简单讲解与实践
- PRML 读书笔记-Chapter1
- Ubuntu 14.04 下搭建SVN独立服务器
- 眼疼
- Android事件总线分发库EventBus3.0的简单讲解与实践
- Effective cpp 读书笔记1
- 数据结构之Trie树
- linux下命令源码
- c++总结01
- Leetcode二分查找类题目
- 第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。
- 为什么udp为什么不能发送大于1472字节数据
- =函数指针