Leecode-Linked List Cycle
来源:互联网 发布:webservice和json区别 编辑:程序博客网 时间:2024/06/01 07:21
Given a linked list, determine if it has a cycle in it.Follow up:Can you solve it without using extra space?
package Leecode;import java.util.HashSet;import java.util.Set; class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } /* * URL:https://oj.leetcode.com/problems/linked-list-cycle/*/ public class LinkedListCycle {//空间O(1),时间O(n^2)public boolean hasCycle(ListNode head) {boolean b = false;ListNode p = head, q = head;if (head != null) {while (q != null && q.next!=null) {q = q.next.next;p = p.next;if (q == p){b = true;break;}}}return b;}//hash,空间O(n),时间O(n)public boolean hasCycle2(ListNode head) {boolean b =false;Set<ListNode>set = new HashSet<ListNode>();while(head != null){if(set.contains(head)){b = true;break;}else{set.add(head);head = head.next;}}return b;}public static void main(String[] args) {}}
拓展:
1、如何知道环的长度?
记录下第一次碰撞点p,slow、fast从该点开始,再次碰撞所走过的操作数就是环的长度s。
2、如何找出环的连接点在哪里?
定理:碰撞点p到连接点的距离=头指针到连接点的距离,因此,分别从碰撞点、头指针开始走,相遇的那个点就是连接点。
方法:记录下第一次碰撞点p,然后设两指针分别从头结点和p开始走,两指针相遇处即为连接点。走的步长为头结点与碰撞点的距离
证明:
链表形状类似数字 6 。
假设甩尾(在环外)长度为 a(结点个数),环内长度为 b 。
则总长度(也是总结点数)为 a+b 。
从头开始,0 base 编号。
将第 i 步访问的结点用 S(i) 表示。i = 0, 1 ...
当 i<a 时,S(i)=i ;
当 i≥a 时,S(i)=a+(i-a)%b 。
分析追赶过程:
两个指针分别前进,假定经过 x 步后,碰撞。则有:S(x)=S(2x)
由环的周期性有:2x=tb+x 。得到 x=tb 。
另,碰撞时,必须在环内,不可能在甩尾段,有 x>=a 。
连接点为从起点走 a 步,即 S(a)。
S(a) = S(tb+a) = S(x+a)。
即S(a) = S(0+a) = S(x+a)
得到结论:从碰撞点 x 前进 a 步即为连接点。
综上,从 x 点和从起点同步前进,第一个碰撞点就是连接点。
3、带环链表的长度是多少?
问题1与2的结果的和。
0 0
- Leecode-Linked List Cycle
- LeeCode-Linked List Cycle
- LeeCode 142 Linked List Cycle II
- 142. Linked List Cycle II [leecode]
- [Leecode]Linked List CycleII
- leecode - Reverse Linked List
- leetcode Linked List Cycle & Linked List Cycle ||
- Linked List Cycle II Linked List Cycle
- LeeCode 206 Reverse Linked List
- LeeCode-Remove Linked List Elements
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- PHP Curl HttpRPC
- Angular.js 学习日志一,入门的开始
- iOS开发 - 得到字符串中出现最多的字符
- ubuntu上的sh链接到dash
- hdu 3966 Aragorn's Story(树链剖分对点编号)
- Leecode-Linked List Cycle
- 【2014/09/16】linux笔记文件权限 脚本
- 魔兽世界WOW服务器端的模拟器【2010】
- 数据库——游标
- 在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误。
- mysql查看用户具有哪些权限
- Linux进程的一生
- 使用第三方库的apk 在Ubuntu下编译后不能正常运行
- 配置DNS服务器