题目:
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例:
代码:
- 解法一
/**
* 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 fast=head;
ListNode slow=head;
while(true){
fast=fast.next.next;
slow=slow.next;
if(fast==null||fast.next==null){
return false;
}
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 fast = head.next.next;
ListNode slow = head;
while(true){
if(fast == null || fast.next == null)
return false;
else if(fast == slow || fast.next == slow)
return true;
else{
fast = fast.next.next;
slow = slow.next;
}
}
}
}