141. 环形链表
141. 环形链表
这个题就是滑冰的时候的兔子战术,等快的链表和慢的链表相等的时候说明必有环。
题目:
题解:
/** * 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 slow = head; ListNode fast = head; while(fast!=null&&fast.next!=null) { slow = slow.next; fast = fast.next.next; //如果快的追上了慢的,说明是环形 if(slow == fast) { return true; } } return false; } }