leetcode141. 环形链表
这里讲快慢指针的解法,hash表要申请额外空间不在这里讲解。
思路:定义快指针一次走两步,慢指针一次走一步,如果存在环,快慢指针一定会相遇。类似两个人在操场跑步,快的人一定会和慢的那个相遇。
/**
* 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;
}
if(head.next == null){
return false;
}//定义快慢指针,让起点不同主要是为了符合下面的循环条件,fast = head.next.next也是可以的。
ListNode fast = head.next;
ListNode slow = head;
while(fast != slow){
if(fast == null||fast.next == null){
return false;
}
fast = fast.next.next;
slow = slow.next;
}
return true;
}
}