12.【链表】Linked List Cycle--Accepted code
来源:互联网 发布:软件售后服务承诺英文 编辑:程序博客网 时间:2024/05/21 09:10
leetcode URL:https://leetcode.com/problems/linked-list-cycle/
解法1 用Hashset实现,利用HashSet在add重复节点时会返回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) return false; HashSet<ListNode> nodeSet=new HashSet<>(); ListNode p=head; nodeSet.add(p); while(p.next!=null){ if(!nodeSet.add(p.next)) return true; p=p.next; } return 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) return false; ListNode s=head; ListNode f=head; while(f!=null && f.next!=null && f.next.next!=null){//判断f.next.next是否为空之前需要先判断f和f.next是否为空,否则会NPE s=s.next; f=f.next.next; if(s==f) return true; } return false; }}
注意:判断f.next.next是否为空之前需要先判断f和f.next是否为空,否则会NPE
0 0
- 12.【链表】Linked List Cycle--Accepted code
- 13.【链表】Reverse Linked List--Accepted code
- CODE 138: Linked List Cycle
- linked-list-cycle Java code
- CODE 139: Linked List Cycle II
- [leet code] Linked List Cycle II
- leetcode 日经贴,Cpp code -Linked List Cycle
- linked-list-cycle-ii Java code
- leetcode Linked List Cycle & Linked List Cycle ||
- Linked List Cycle II Linked List Cycle
- leetcode 日经贴,Cpp code -Linked List Cycle II
- Leetcode 链表 Linked List Cycle II
- [leetcode] 【链表】141. Linked List Cycle
- [leetcode] 【链表】142. Linked List Cycle II
- leetcode_c++:链表:Linked List Cycle(141)
- leetcode_c++:链表:Linked List Cycle II(142)
- leetcode_c++:链表:Linked List Cycle II(142)
- Leetcode#141(链表)-Linked List Cycle
- Android设备连接Unity Profiler性能分析器
- 算法学习之素数
- redis的linux下的单机安装、集群安装及测试
- 写操作系统只能用汇编和C语言吗
- git本地仓库连接多远程
- 12.【链表】Linked List Cycle--Accepted code
- 为什么在6plus上打印的屏幕高度是6的高度
- cookie&session
- 为什么使用python
- [学习资源]
- 总结抽象类与接口的关联和区别
- 关于安装cocoapods遇到的一些坑(ERROR: Error installing cocoapods: activesupport requires Ruby version >= 2.2)
- Android权限大全
- 学习笔记-递归函数