LeetCode-探索-初级算法-链表-6. 环形链表(个人做题记录,不是习题讲解)
LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/
- 环形链表
-
语言:java
-
思路:没想出来,后面听网上说,可以用两个指针a和b,b走2格,a走1格,要是最后遇上了就是环,最后如果b是null就没有环路。
-
代码(0ms):
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { ListNode cur = head,next = head; while(next!=null&&next.next!=null){ next = next.next.next; cur = cur.next; if(next == cur) return true; } return false; } }
本文介绍了一种使用双指针技术检测链表中是否存在环的高效算法。通过一个指针每次移动一步,另一个指针每次移动两步,若两者相遇则表明链表有环。此方法适用于初级算法学习,特别针对LeetCode上的环形链表问题。
1437

被折叠的 条评论
为什么被折叠?



