CODE 138: Linked List Cycle
2013-11-24 16:07
218 查看
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
public boolean hasCycle(ListNode head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(null == head){
return false;
}
ListNode first = head;
ListNode second = head;
while(first.next != null && first.next.next !=null){
if(first.next.equals(second) || first.next.next.equals(second)){
return true;
}
first = first.next.next;
second = second.next;
}
if(first.next != null && first.next.equals(second)){
return true;
}
return false;
}
Follow up:
Can you solve it without using extra space?
public boolean hasCycle(ListNode head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(null == head){
return false;
}
ListNode first = head;
ListNode second = head;
while(first.next != null && first.next.next !=null){
if(first.next.equals(second) || first.next.next.equals(second)){
return true;
}
first = first.next.next;
second = second.next;
}
if(first.next != null && first.next.equals(second)){
return true;
}
return false;
}
相关文章推荐
- [leet code] Linked List Cycle II
- CODE 139: Linked List Cycle II
- LeedCode:Linked List Cycle II
- [LeedCode OJ]#142 Linked List Cycle II
- leecode 解题总结:141. Linked List Cycle
- [LeedCode OJ]#141 Linked List Cycle
- leecode 解题总结:142. Linked List Cycle II
- linked-list-cycle-ii Java code
- leedcode做题总结,题目Linked List Cycle I/II 13/10/28-30
- linked-list-cycle Java code
- LeetCode-Linked List Cycle
- 【面试准备】letcode-Linked List Cycle ||
- leetcode || 142、Linked List Cycle II
- Linked List Cycle II
- 141. Linked List Cycle
- Linked List Cycle II
- LeetCode - Linked List Cycle II
- Leetcode_141_Linked List Cycle
- Linked List Cycle
- Leetcode-linked-list-cycle-ii