博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Linked List Cycle II
阅读量:4640 次
发布时间:2019-06-09

本文共 1546 字,大约阅读时间需要 5 分钟。

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?

分析:和类似,还是用map。

用时:60ms

1 /** 2  * Definition for singly-linked list. 3  * struct ListNode { 4  *     int val; 5  *     ListNode *next; 6  *     ListNode(int x) : val(x), next(NULL) {} 7  * }; 8  */ 9 class Solution {10 public:11     ListNode *detectCycle(ListNode *head) {12         map
m;13 while(head){14 if(m.find(head) == m.end()) m[head] = true;15 else return head;16 head = head->next;17 }18 return NULL;19 }20 };

 

同时,对于中的较优方法,同样适用于本题。当fast和slow指针相遇时,令设指针slow2 = head,那么slow2和slow一定会在相遇的地方重合。

用时:16ms

1 /** 2  * Definition for singly-linked list. 3  * struct ListNode { 4  *     int val; 5  *     ListNode *next; 6  *     ListNode(int x) : val(x), next(NULL) {} 7  * }; 8  */ 9 class Solution {10 public:11     ListNode *detectCycle(ListNode *head) {12         ListNode *fast = head, *slow = head;13         while(fast && fast->next){14             fast = fast->next->next;15             slow = slow->next;16             if(fast == slow){17                 ListNode* slow2 = head;18                 while(slow){19                     if(slow2 == slow) return slow;20                     slow = slow->next;21                     slow2 = slow2->next;22                     23                 }24             }25         }26         return NULL;27     }28 };

转载于:https://www.cnblogs.com/amazingzoe/p/4518313.html

你可能感兴趣的文章
BZOJ 1613: [Usaco2007 Jan]Running贝茜的晨练计划
查看>>
ubuntu 重启命令,ubuntu 重启网卡方法
查看>>
Linux的学习:
查看>>
JavaScript中的原型继承原理
查看>>
Python logger模块
查看>>
jquery控制css的display(控制元素的显示与隐藏)
查看>>
关于python做人工智能的一个网页(很牛逼)
查看>>
判断控件的CGRect是否重合,获取控件的最大XY值
查看>>
POJ-1128 Frame Stacking
查看>>
异常体系
查看>>
String.format(转)
查看>>
解决 CS0006 未能找到元数据文件
查看>>
HDU 5131.Song Jiang's rank list (2014ACM/ICPC亚洲区广州站-重现赛)
查看>>
mysql搭建主从数据库
查看>>
新的一年,新的开始
查看>>
python模块struct
查看>>
图像的灰度级和动态范围(转)
查看>>
C# MODBUS协议 上位机(转)
查看>>
CSS box-shadow 属性
查看>>
vue:图片切换动态显示
查看>>