随笔- 509  文章- 0  评论- 151  阅读- 22万 

Linked List Cycle

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 };
复制代码

 

 posted on   zhuli19901106  阅读(258)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示