Linked List Cycle II 求单链表环的入口
来源:互联网 发布:科蓝软件 编辑:程序博客网 时间:2024/06/06 16:25
Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /* 假设ptr1需要m步第一次走到环的开始节点,那么ptr2应该走到了环的第m个位置(注意:这里是指环里的位置,ptr1在0处,ptr2在m处)。ptr2每次都比ptr1多走一步且它们都在环内,所以需要n-m步(n是环的大小),才能追上ptr1,达到重合。这个重合位置是[2*(n-m)+m-x*n]%n=n-m,这样我们就可以知道,重合的位置距离环开始节点有m步,head距离环开始节点也是m步。 */class Solution {public: ListNode *detectCycle(ListNode *head) { if(head==NULL) return NULL; ListNode *slow,*fast; slow=head; fast=head; int f=0; while(fast!=NULL&&fast->next!=NULL) { fast=fast->next->next; slow=slow->next; if(slow==fast) { f=1; break; } } if(!f) return NULL; slow=head; while(slow!=fast) { slow=slow->next; fast=fast->next; } return slow; }};
0 0
- Linked List Cycle II 求单链表环的入口
- Linked List Cycle II 链表环的入口
- 求单链表环的入口结点 Linked List Cycle II
- Linked List Cycle II 找链表环入口 @LeetCode
- Leetcode Linked List Cycle II 循环链表入口
- Linked List Cycle leetcode II java (寻找链表环的入口)
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- HDOJ 不可摸数 1999
- 文章标题
- Linked List Cycle 判断链表是否有环
- 实现和IE浏览器交互的几种方法的介绍
- SandBox基本机制
- Linked List Cycle II 求单链表环的入口
- CocoaPods使用遇到的问题
- 标准C++中有四个类型转换符
- 改变图像的对比度和亮度-----学习记录(4)
- cocos2d-x
- Reorder List 链表位置的变换 数组处理
- Android:Otto源码分析
- JMS 服务器ActiveMQ Queue和Topic区别
- 解决远程连接mysql很慢的方法(mysql_connect 打开连接慢)