【算法】链表判断是否有环
2021/7/1 17:25:01
本文主要是介绍【算法】链表判断是否有环,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
class ListNode{ int val; ListNode next; ListNode(int x){ this.val = x; next = null; }
思路一:用哈希表存储遍历所有节点
每个访问的节点,放入哈希表中,如果下一个节点已经存在于哈希表中,表示有环
时间和空间复杂度都是O(N)
//hash public boolean hasCycleWithHash(ListNode head){ Set<ListNode> listNodeSet = new HashSet<>(); while (head != null){ if(!listNodeSet.add(head)){ return true; } else { head = head.next; } } return false; }
思路二:快慢指针
同时出发,如果有环,跑的快的指针一定会和慢指针再次相遇
时间复杂度O(N),空间复杂度O(1)
//do while public boolean hasCycleWithFastSlow(ListNode head) { if (head == null || head.next == null){ return false; } ListNode fast = head; ListNode slow = head; do { //判断前面的兔子有没有走到头,走到头,跳出循环 if (fast == null || fast.next == null) { return false; } //自身移动 slow = slow.next; fast = fast.next.next; } while (fast != slow); return true; }
换while结构,初始化slow和fast的差别
//while public boolean hasCycleMethod(ListNode head) { if (head == null || head.next == null) { return false; } 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; } return true; }
这篇关于【算法】链表判断是否有环的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?