判断链表是否存在环

使用双指针,一个指针每次移动一个节点,一个指针每次移动两个节点,如果存在环,那么这两个指针一定会相遇。

之前剑指有类似的题

 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         if(head==null) return false;
15         ListNode slow = head;
16         ListNode fast = head;
17         while(slow!=null&&fast!=null&&slow.next!=null&&fast.next!=null&&fast.next.next!=null){
18             slow=slow.next;
19             fast=fast.next.next;
20             if(slow==fast) return true;
21         }
22         return false;
23     }
24 }

 

posted @ 2019-09-23 19:28  chyblogs  阅读(149)  评论(0)    收藏  举报