【LeetCode】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?

java code : 很简单的判断单链表是否有环。

/**
 * 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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(head == null || head.next == null)
			return false;
		ListNode p = head, q = head.next;
		while( q!= null && q.next != null)
		{
			if(p == q)
				return true;
			p = p.next;
			q = q.next.next;
		}
		return false;
    }
}


你可能感兴趣的:(java,LeetCode,单链表)