Linked List Cycle - LeetCode
2014-02-21 14:20
316 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/**
* 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 current = head;
ListNode current2 = current.next;
while(current2 != null){
if((current!=null)&&(current2.next!=null)){
current = current.next;
current2 = current2.next.next;
}
else{
return false;
}
if(current == current2)
return true;
}
return false;
}
}
Follow up:
Can you solve it without using extra space?
/**
* 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 current = head;
ListNode current2 = current.next;
while(current2 != null){
if((current!=null)&&(current2.next!=null)){
current = current.next;
current2 = current2.next.next;
}
else{
return false;
}
if(current == current2)
return true;
}
return false;
}
}
相关文章推荐
- LeetCode Linked List Cycle II
- LeetCode之Linked List Cycle II
- [Leetcode]Linked List Cycle
- LeetCode--Linked List Cycle
- leetCode Linked List Cycle 解题分享
- [LeetCode] Linked List Cycle
- LeetCode – Refresh – Linked List Cycle
- [Leetcode]Linked List Cycle
- leetcode - Linked List Cycle II
- LeetCode (27) Linked List Cycle (判断cycle存在、寻找cycle入口节点)
- LeetCode题解——Linked List Cycle
- [LeetCode]Linked List Cycle II
- LeetCode 学习 LinkedList 专项(5)—— Linked List Cycle
- [leetcode] Linked List Cycle
- leetCode--linked-list-cycle-ii
- 【题解】【链表】【Leetcode】Linked List Cycle II
- LeetCode OJ Linked List Cycle II
- leetcode: Linked List Cycle II
- leetcode解题之141# Linked List Cycle Java版 (判断链表是否有环)
- Leetcode: Linked List Cycle II