Detect loop in a singly linked list
去Twitter面试的被问到这个问题,当时只想到了用HashMap的办法,这种办法时间复杂度O(n),空间复杂度是O(n), 更好的办法是用 FastRunner / SlowRunner approach。用两个pointer遍历链表,fast的速度是slow的两倍,如果有loop,二者一定会collide。
boolean detectLoop(LinkedListNode head){
LinkedList slow = head;
LinkedList fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
return false;
}
What if we want to find the start of the loop?
Detect loop in a singly linked list的更多相关文章
- LeetCode 206 Reverse a singly linked list.
Reverse a singly linked list. Hint: A linked list can be reversed either iteratively or recursively. ...
- [LintCode] Delete Node in the Middle of Singly Linked List 在单链表的中间删除节点
Implement an algorithm to delete a node in the middle of a singly linked list, given only access to ...
- Singly Linked List
Singly Linked List Singly linked list storage structure:typedef struct Node{ ElemType data; struct N ...
- Reverse a singly linked list
Reverse a singly linked list. /** * Definition for singly-linked list. * struct ListNode { * int val ...
- [cc150] check palindrome of a singly linked list
Problem: Implement a function to check if a singly linked list is a palindrome. 思路: 最简单的方法是 Reverse ...
- 单链表反转(Singly Linked Lists in Java)
单链表反转(Singly Linked Lists in Java) 博客分类: 数据结构及算法 package dsa.linkedlist; public class Node<E> ...
- [TS] Implement a singly linked list in TypeScript
In a singly linked list each node in the list stores the contents of the node and a reference (or po ...
- [轉]Reverse a singly linked list
Reverse a singly linked list http://angelonotes.blogspot.tw/2011/08/reverse-singly-linked-list.html ...
- Singly linked list algorithm implemented by Java
Jeff Lee blog: http://www.cnblogs.com/Alandre/ (泥沙砖瓦浆木匠),retain the url when reproduced ! Thanks ...
随机推荐
- Tomcat - DBCP 配置
1. Database configuration Create a new test user, a new database and a single test table. Your MySQL ...
- 【ANT】ant概述
ANT是集软件测试.编译.打包.部署等自动化构建工具,是Apache软件基金会JAKARTA目录中的一个子项目,具有以下优点: 跨平台性 ANT是由Java语言编写,具有很好的跨平台性. 操作简单 A ...
- Dalvik字节码的类型,方法与字段表示方法
Dalvik字节码有着自己的类型,方法与字段表示方法,这些方法与Dalvik虚拟机指令集一起组成了一条条的Dalvik汇编代码. 1.类型 Dalvik字节码只有两种类型,基本类型与引用类型.Dalv ...
- MYfirst
终于有了自己的博客了,啊哈哈!
- 和阿文一起学H5-- H5排版八大套路
二.中心型 三.倾斜型 四.三角形 5.全图形 6.渐变型 7.蒙版型 \ 8.骨骼型 实例
- using System.Threading;
/// <summary> /// 执行动作:耗时而已 /// </summary> private void TestThread(string threadName) { ...
- jQuery实现CheckBox全选、全不选
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 代码优化—From <effective C++>
1.尽可能的延后变量定义式的出现时间 不止应该延后变量的定义,直到非得使用该变量的前一刻为止,甚至应该尝试延后这份定义直到能够给它初值实参为止. 如果这样不仅能够避免构造和析构非必要对象,还可以避免无 ...
- 2013山东省“浪潮杯”省赛 A.Rescue The Princess
A.Rescue The PrincessDescription Several days ago, a beast caught a beautiful princess and the princ ...
- HotSpot算法实现
1.枚举根节点 可作为GC Roots的节点主要在全局性的引用(例如常量或类静态属性)与执行上下文(例如栈帧中的本地变量表)中. 可达性分析对执行时间的敏感体现在GC停顿上,因为分析工作必须在能确保一 ...