141. 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?
use hash map to save node.
Two pointers with different speed.
/**
* 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 p = head, q = head.next;
while(p != null && q != null){
if(p == q) return true;
p = p.next;
q = q.next;
if(q != null) q = q.next;
}
return false;
}
}