141 Linked List Cycle
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
两个指针,一个一次走 2 步,一个一次走 1 步,如果快的走到头,说明没有环,有环两个指针必然相遇,如果相遇说明有环。时间复杂度 o(n) ,空间复杂度 o(1)
public boolean hasCycle(ListNode head) {
if(head==null) return false;
ListNode l1=head, l2=head;
while(l2!=null && l2.next!=null){
l2=l2.next.next;
l1=l1.next;
if(l2==l1) return true;
}
return false;
}
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL) return false;
ListNode * l1=head;
ListNode * l2=head;
while(l2!=NULL && l2->next!=NULL){
l2=l2->next->next;
l1=l1->next;
if(l1==l2) return true;
}
return false;
}
};
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if head is None:
return False;
p1=head
p2=head
while p2 and p2.next:
p2=p2.next.next
p1=p1.next
if p1 is p2:
return True
return False
这道题有人找到测试用例中链表的最大长度,然后面向测试用例编程。。。
(测试用例是会变的,现在已经扩充到 10000)
public class Solution {
public boolean hasCycle(ListNode head) {
int count = 8029;
while( head != null && count > 0){
head = head.next;
count--;
}
if( head == null ) return false;
return true;
}
}