数据结构--链表刷题(一)快慢指针(下)

简介: 数据结构--链表刷题(一)快慢指针

数据结构--链表刷题(一)快慢指针(上)

https://developer.aliyun.com/article/1480781?spm=a2c6h.13148508.setting.14.5f4e4f0eUFaP8y

2.判断是否带环

https://leetcode.cn/problems/linked-list-cycle/description/

代码实现:

1.快慢指针

 
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null || head.next == null) return false;
 
        ListNode fast = head;
        ListNode slow = head;
 
        // 只要有环 则fast和slow一定会相遇
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
 
            if(fast == slow) return true;
        }
 
        return false;
        
    }
}

2.使用哈希表

public class Solution {
    public boolean hasCycle(ListNode head) {
        Set<ListNode> seen = new HashSet<ListNode>();
        while(head != null) {
            if(!seen.add(head)) {
                return true;
            }
 
            head = head.next;
        }
 
        return false;
        
    }
}

2.环形链表的进阶

https://leetcode.cn/problems/linked-list-cycle-ii/submissions/

代码实现:

1.哈希表的实现
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode cur = head;
        Set<ListNode> seen = new HashSet<>();
 
        while(cur != null) {
            // 如果包含  则证明走到了入口点
            if(seen.contains(cur)) {
                return cur;
            }else {
                seen.add(cur);
            }
 
            cur = cur.next;
        }
 
        return null;
    }
}
 
2.双指针
public class Solution {
    public ListNode detectCycle(ListNode head) {
 
 
        // 先找相遇点
        ListNode fast = head;
        ListNode slow = head;
 
 
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
 
 
            if(fast == slow) break;
        }
 
 
        // 跳出循环有两种condition
        if(fast == null || fast.next == null) return null;
 
 
        // fast = head  两个指针一起走 直到相同
        fast = head;
        while(fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
 
 
        return slow;
    }
}


目录
相关文章
|
20天前
|
算法 容器
OJ刷题日记:2、双指针(2)
OJ刷题日记:2、双指针(2)
16 0
|
12天前
|
存储
数据结构第二课 -----线性表之单向链表
数据结构第二课 -----线性表之单向链表
|
3天前
|
存储 算法 Java
数据结构与算法 数组和链表
数据结构与算法 数组和链表
8 0
|
3天前
|
存储 Java
深入浅出数据结构之链表
深入浅出数据结构之链表
|
3天前
|
C++
数据结构(双链表
数据结构(双链表
7 1
|
3天前
|
算法 测试技术 容器
【刷题】双指针进阶
请看入门篇 :双指针入门
11 0
【刷题】双指针进阶
|
4天前
|
算法 测试技术 容器
【刷题】双指针入门
经过这四道题目的洗礼,我大概对双指针有了初步印象,接下来我会继续努力!!!
43 13
【刷题】双指针入门
|
6天前
|
存储 缓存
[数据结构]~双向+循环链表从(0~1)
[数据结构]~双向+循环链表从(0~1)
|
12天前
|
存储
数据结构第三课 -----线性表之双向链表
数据结构第三课 -----线性表之双向链表
|
13天前
|
存储 Java
数据结构奇妙旅程之顺序表和链表
数据结构奇妙旅程之顺序表和链表