142. Linked List Cycle II
来源:互联网 发布:视频噪声消除软件 编辑:程序博客网 时间:2024/05/12 02:00
先看141. Linked List Cycle 。
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; }};
0 0
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- java 线程二
- JSP+Servlet+JavaBean传统方式实现简易留言板制作(注册、登录、留言)
- java学习笔记
- Spring之FactoryBean
- Spring IOC容器-注解的方式【更简化】
- 142. Linked List Cycle II
- Android中的IPC方式(一)—— Bundle、文件共享、Messenger
- 反编译android中的xml文件
- 请实现一个函数,把字符串中的每个空格替换成“ ”
- Android播放声音文体
- 大搬家 2015百度之星资格赛
- Android app集成友盟微社区详细步骤
- NLTK自然语言处理2
- 广播