经典快慢指针找环问题
package Level2;
import Utility.ListNode;
/**
* Linked List Cycle
*
* Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
*
*/
public class S127 {
public static void main(String[] args) {
}
// 经典快慢指针找环问题
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while(true){
if(fast==null || fast.next==null || slow==null){
return false;
}
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
return true;
}
}
}
}
/**
* 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 slow = head;
ListNode fast = head;
while(fast!=null && fast.next!=null && slow!=null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
return true;
}
}
return false;
}
}

374

被折叠的 条评论
为什么被折叠?



