题解 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
import java.util.*;
/**
* 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) {
// 解题思路:从相同位置出发,一个步长为1,一个步长为2,如果有环最终会相遇
if(head == null){
return false;
}
ListNode n1 = head;
ListNode n2 = head;
while(n2 != null && n2.next != null){
n1 = n1.next;
n2 = n2.next.next;
if(n1 == n2){
return true;
}
}
return false;
}
}
深信服公司福利 851人发布