2014.1.13 21:24
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Solution:
The problem indicated that you shouldn't use extra space. And you might be wondering why you should use extra space if you could just use two pointers and let the faster one chase up the slower one.
If extra space is allowed, you can use a hash-table to record the addresses of the nodes. There will be duplicate address if the list contains a cycle.
I guess you're more familiar with the chasing method, which uses extra chasing time to avoid the space usage in hashing.
Time complexity is O(n), space complexity is O(1).
Accepted code:
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 bool hasCycle(ListNode *head) { 12 // IMPORTANT: Please reset any member data you declared, as 13 // the same Solution instance will be reused for each test case. 14 if(head == nullptr){ 15 return false; 16 } 17 18 ListNode *p1, *p2; 19 20 p1 = p2 = head; 21 while(true){ 22 if(p1->next == nullptr){ 23 return false; 24 } 25 if(p2->next == nullptr || p2->next->next == nullptr){ 26 return false; 27 } 28 29 p1 = p1->next; 30 p2 = p2->next->next; 31 if(p1 == p2){ 32 // Same address, same node 33 // There is a cycle in the list 34 return true; 35 } 36 } 37 } 38 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)