Leetcode Linked List Cycle
2016-07-06 02:54
471 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Difficulty: Easy
Solution 1: HashSet
/**
* 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) {
HashSet<ListNode> set = new HashSet<ListNode>();
while(head!=null){
if(set.contains(head))
return true;
set.add(head);
head = head.next;
}
return false;
}
}
Solution 2: Two pointers
/**
* 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 || head.next == null) return false;
ListNode curr = head.next;
ListNode currTwo = head.next.next;
while(currTwo != null){
if(curr == currTwo)
return true;
if(currTwo.next == null) return false;
curr = curr.next;
currTwo = currTwo.next.next;
}
return false;
}
}
Follow up:
Can you solve it without using extra space?
Difficulty: Easy
Solution 1: HashSet
/**
* 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) {
HashSet<ListNode> set = new HashSet<ListNode>();
while(head!=null){
if(set.contains(head))
return true;
set.add(head);
head = head.next;
}
return false;
}
}
Solution 2: Two pointers
/**
* 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 || head.next == null) return false;
ListNode curr = head.next;
ListNode currTwo = head.next.next;
while(currTwo != null){
if(curr == currTwo)
return true;
if(currTwo.next == null) return false;
curr = curr.next;
currTwo = currTwo.next.next;
}
return false;
}
}
相关文章推荐
- HDU 4608 I-number(暴力模拟)
- Retrofit源码分析
- 三维几何专题
- window下执行.sh文件的方法
- Digit Counts
- 【我的《冒号课堂》学习笔记】设计原则(3)内聚原则
- VS未找到与约束ContractName Microsoft.VisualStudio.Text.ITextDocumentFactoryService
- scala集合API使用
- A + B Problem
- 关键字
- tomcat源码解析(二)--web.xml文件的解析
- Trailing Zeros
- 简单题:不等式(知道了运算符号算是字符可以定义为char类型)待解决
- How do I divide matrix elements by column sums in MATLAB?
- Linux上创建和更改硬链接和符号链接
- 【我的《冒号课堂》学习笔记】设计原则(2)依赖原则
- RHEL 7.0系统安装配置图解教程
- Reverse Pairs
- The Concept of Indistinguishability under Chosen Plaintext Attack (IND-CPA)
- UITableView滚动时NSTimer不执行