环形链表
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
/**
* 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) {
while(head!=null){
if(head==head.next){
return true;
}
if(head.next!=null){
head.next=head.next.next;
}
head=head.next;
}
return false;
}
}
执行结果:通过
执行用时 :0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗 :41.3 MB, 在所有 Java 提交中击败了5.02%的用户
思路:当 head.next 不为空时,将head.next 指向 head.next.next,相当于去掉了next节点,到最后如果有环,head == head.next。
来源:CSDN
作者:永不褪色的蓝
链接:https://blog.csdn.net/weixin_46442834/article/details/104757432