给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:使用快慢双指针,如果快双指针赶上了慢双指针,即为循环链表
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:39.8 MB, 在所有 Java 提交中击败了13.50%的用户
/**
* 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) {
if(head==null)
{
return false;
}
ListNode i=head;
ListNode j=head;
while(j!=null&&j.next!=null)
{
i=i.next;
j=j.next.next;
if(j==i)
{
return true;
}
}
return false;
}
}
执行用时:64 ms, 在所有 Python3 提交中击败了52.14%的用户
内存消耗:18.2 MB, 在所有 Python3 提交中击败了22.81%的用户
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if head==None :
return False
i=head
j=head
while j!=None and j.next!=None:
i=i.next
j=j.next.next
if i==j:
return True
return False