leetcode--Linked List Cycle
2017-08-08 12:45
302 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
[java] view
plain copy
/**
* 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 slow = head.next;
ListNode fast = null;
if(slow==null) return false;
else fast = slow.next;
while(slow!=null&&fast!=null){
if(slow==fast) return true;
else{
slow = slow.next;
if(fast.next!=null) fast = fast.next.next;
else return false;
}
}
return false;
}
}
原文链接http://blog.csdn.net/crazy__chen/article/details/46563843
Follow up:
Can you solve it without using extra space?
[java] view
plain copy
/**
* 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 slow = head.next;
ListNode fast = null;
if(slow==null) return false;
else fast = slow.next;
while(slow!=null&&fast!=null){
if(slow==fast) return true;
else{
slow = slow.next;
if(fast.next!=null) fast = fast.next.next;
else return false;
}
}
return false;
}
}
原文链接http://blog.csdn.net/crazy__chen/article/details/46563843
相关文章推荐
- LeetCode|Linked List Cycle
- LeetCode Linked List Cycle II
- LeetCode_Linked List_Linked List Cycle
- Leetcode- List - Linked List Cycle
- leetcode-141&142 Linked List Cycle I & II
- [LeetCode] Linked List Cycle II 链表环起始位置
- [leetcode][list][two pointers] Linked List Cycle
- leetcode解题之141# Linked List Cycle Java版 (判断链表是否有环)
- [Leetcode] Linked List Cycle (Java)
- leetcode — linked-list-cycle
- [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, Solution
- [leetcode] Linked List Cycle II
- leetcode---linked-list-cycle-ii---链表
- LeetCode Linked List Cycle II
- LeetCode Linked List Cycle (Floyd判圈算法)