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'snext
pointer is connected to. Note thatpos
is not passed as a parameter.Return
true
if there is a cycle in the linked list. Otherwise, returnfalse
.给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
进阶:
你能用 O(1)(即,常量)内存解决此问题吗?
Example 1:
Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).Example 2:
Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.Example 3:
Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list.Constraints:
- The number of the nodes in the list is in the range
[0, 104]
.-105 <= Node.val <= 105
pos
is-1
or a valid index in the linked-list.Follow up: Can you solve it using
O(1)
(i.e. constant) memory?
这一题的思路也有两种思路,不过我还是只想到了一种,利用双指针的方法,还有一种方法是用哈希表,我们先来看看如何使用双指针来完成。
其实就是创建两个指针,一个快指针,一个慢指针,然后两个指针进行依次的遍历,当两个指针有重合的时候,就返回true,没有重合的时候就返回false。
下面看看代码
/**
* 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 || head.next != null) return fasle;
ListNode slow = head;
ListNode fast = head.next;
while(slow != fast){
if(fast == null || fast.next == null) return false;
slow = slow.next;
fast = fast.next.next;//保证能够追上slow
}
return true;
}
}
下面一个方法是用哈希表,思路就是用哈希表存储已经遍历过的结点,如果再次遇到就返回true,遇不到就返回fasle
下面看看代码
/**
* 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) {
Set<ListNode> set = new HashSet<ListNode>();
if(head == null || head.next == null) return false;
while(head != null){
if(set.add(head) != fasle){
return true;//set.add()方法如果哈希表中有数据就返回fasle,没有就返回true。
}
head = head.next;
}
return false;
}
}
此时使用哈希表来记录数值,并进行后续的判断。大家可以记一下这个用法。