LeetCode 141. Linked List Cycle 判断链表是否有环 C++/Java

时间:2022-05-11 03:21:59

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer poswhich represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
LeetCode 141. Linked List Cycle 判断链表是否有环 C++/Java

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

LeetCode 141. Linked List Cycle 判断链表是否有环 C++/Java

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
LeetCode 141. Linked List Cycle 判断链表是否有环 C++/Java
判断链表是否有环:使用快慢指针去判断,如果有环,fast快指针先进入环,slow慢指针后进入,经过一定步的操作,快慢指针在环上相遇。
方法一:(C++)
 class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast=head,*slow=head;
while(fast&&fast->next){
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
return true;
}
return false;
}
};
方法二:(Java)
 public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> s=new HashSet();
while(head!=null){
if(s.contains(head))
return true;
else
s.add(head);
head=head.next;
}
return false;
}
}

Java集合中含有contains()方法,判断其是否已经含有此节点,如果没有,则使用add()添加进去