二、环形链表
本题给了我们一个链表的头节点,需要我们判断这个链表之中是否存在环状结构,如果存在返回true,如果不存在则返回false。
1.hash表
我们可以从头遍历整个链表,并将遍历到的节点放入一个hashset中,当我们遍历到的节点与hashset中的节点出现重复时就说明链表存在环,如果我们遍历完了整个链表那就说明不存在环,具体代码如下:
/**
* 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 false;
}
ListNode node = head;
HashSet<ListNode> set = new HashSet<>();
while(node != null) {
if(set.contains(node)) {
return true;
}
set.add(node);
node = node.next;
}
return false;
}
}
复杂度分析
- 时间复杂度:O(n)。
- 空间复杂度:O(n)。
2.双指针
我们可以定义两个指针来遍历这个链表,慢指针每次走一个节点,快指针每次走两个节点,如果在遍历的过程中快指针与慢指针相遇则说明有环,否则就没有环,具体代码如下:
/**
* 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 false;
}
ListNode f = head;
ListNode s = head;
while(f != null && f.next != null) {
f = f.next.next;
s = s.next;
if(f == s) {
return true;
}
}
return false;
}
}
复杂度分析
- 时间复杂度:O(n)。
- 空间复杂度:O(1)。