给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
思路:刚开始想着让他循环下去,直到和头结点相同的时候,就返回 true,否则就返回 false,但还是 too young too naive。
实际上还是设置两个指针,一个快指针和一个慢指针,只要是在环里面,总会相遇的,就可 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;
listNode low = head;
while( fast != null){
if(fast == low){
return false;
}else{
fast = fast.next;
if(fast.next == null){
return false;
}else{
fast = fast.next;
low = low.next;
}
}
}
return false;
}
}
大神思路:其实也差不多,但是使用 break 语句,和 result 之后比较简洁。
public class Solution {
public boolean hasCycle(ListNode head) {
boolean result = false;
ListNode temp = head;//0
if(head == null || head.next == null) return false;
ListNode fastTemp = head.next;//1
while(fastTemp.next != null) {//2
fastTemp = fastTemp.next;
if(fastTemp == temp) {
result = true;
break;
}
if(fastTemp.next != null) {
fastTemp = fastTemp.next;
temp = temp.next;
}else {
break;
}
}
return result;
}
}