141. Linked List Cycle
- Total Accepted: 145611
- Total Submissions: 405510
- Difficulty: Easy
- Contributors: Admin
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
思路:两个指针,一快一慢,只要是圈,慢的一定能追上快的
/**
* 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) {
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast==slow)return true;
}
return false;
}
}