【leetcode刷题笔记】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?


 

题解:参见http://www.cnblogs.com/sunshineatnoon/p/3825032.html

代码如下:

复制代码
 1 /**
 2  * Definition for singly-linked list.
 3  * class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public boolean hasCycle(ListNode head) {
14         ListNode p1 = head;
15         ListNode p2 = head;
16         
17         while(p2 != null){
18             p1 = p1.next;
19             p2 = p2.next;
20             if(p2 != null)
21                 p2 = p2.next;
22             else 
23                 return false;
24             if(p1 == p2)
25                 return true;
26         }
27         return false;
28     }
29 }
复制代码

 

posted @   SunshineAtNoon  阅读(137)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示