leetcode: Linked List Cycle

http://oj.leetcode.com/problems/linked-list-cycle/

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

思路

这个问题是面试时很常见的问题,但是要求写代码的比较少。最简单的方法就是两个指针,一个每次走一步,一个每次走两步,等赶上了就说明有环。

复制代码
 1 class Solution {
 2 public:
 3     bool hasCycle(ListNode *head) {
 4         if (NULL == head) {
 5             return false;
 6         }
 7         
 8         ListNode *curr = head, *next = head->next;
 9         
10         while (true) {
11             curr = curr->next;
12             
13             int steps = 0;
14             
15             while ((next != NULL) && (steps < 2)) {
16                 next = next->next;
17                 ++steps;
18             }
19             
20             if (NULL == next) {
21                 return false;
22             }
23             
24             if (curr == next) {
25                 return true;
26             }
27         }
28     }
29 };
复制代码

 

posted @   移山测试工作室黑灯老师  阅读(207)  评论(0编辑  收藏  举报
编辑推荐:
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
阅读排行:
· dotnet 源代码生成器分析器入门
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 一文搞懂MCP协议与Function Call的区别
· 一次Java后端服务间歇性响应慢的问题排查记录
count website visits
Buy Computers
点击右上角即可分享
微信分享提示