Linked List Cycle II 找链表环入口 @LeetCode
来源:互联网 发布:网络推广整合方案 编辑:程序博客网 时间:2024/05/17 00:56
经典链表环的问题
package Level3;import Utility.ListNode;/** * Linked List Cycle II * * Given a linked list, return the node where the cycle begins. If there is no cycle, return null.Follow up:Can you solve it without using extra space? * */public class S130 {public static void main(String[] args) {}public ListNode detectCycle(ListNode head) {if(head == null || head.next ==null){return null;}ListNode slow = head;ListNode fast = head;// 找到第一次相遇点while(fast!=null && fast.next!=null && slow!=null){slow = slow.next;fast = fast.next.next;if(slow == fast){// 相遇break;}}// 检查是否因为有环退出或是因为碰到null而退出if(slow==null || fast==null || fast.next==null){return null;}// 把慢指针移到链表头,然后保持快慢指针同样的速度移动// 再次相遇时即为环的入口slow = head;while(slow != fast){slow = slow.next;fast = fast.next;}// 现在快慢指针都指向环的入口return slow;}}
重写时的注意点写在注解里了
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { if(head==null || head.next==null){ return null; // No node or single node ==> No cycle } ListNode fast = head; ListNode slow = head; while(fast!=null && fast.next!=null && slow!=null){ fast = fast.next.next; slow = slow.next; if(fast == slow){ break; } } if(fast != slow){ // no cycle return null; } slow = head; while(fast!=null && slow!=null){ if(fast == slow){ // Check first! eg: 1,2 break; } fast = fast.next; slow = slow.next; } return fast; }}
- Linked List Cycle II 找链表环入口 @LeetCode
- Leetcode Linked List Cycle II 循环链表入口
- Linked List Cycle II 链表环的入口
- Linked List Cycle II 求单链表环的入口
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- Android使用嵌入式关系型SQLite数据库存储数据
- 介绍一下Android的开机流程
- Android 面试题(有详细答案)
- OpenVZ Web Panel
- 使用MultipartEntity上传文件(带进度对话框)
- Linked List Cycle II 找链表环入口 @LeetCode
- 安装Qtcreater时出现“无法解决软件包依赖”错误
- asp.net中split函数的用法
- Linux CentOS 6.3 安装配置VNC服务
- SQL中使用WITH AS提高性能-使用公用表表达式(CTE)简化嵌套SQL
- 重定向和管道
- 我来了
- 基于xmpp实现android端实现即时通讯---asmack基本方法(二)
- python里的get_page函数