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; } }