Given a linked list, determine if it has a cycle in it.
Input: head =[3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

input中的值不代表具体数值,只有input中含有null时候或者单个数字时候才代表链表不循环!


Input: head = [1], pos = -1
Output: false
Explanation: There is no
cycle in the linked list.


判断链表是否构成环路,采用双指针方法,head头指针每次移动一个,另一个指针每次从第二次开始移动两个,第一次由于存在单个元素构成cycle,故第一次应移动一个。
/**
 * 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 head = l1,l2=head.next;
    	//若有循环,两个指针不为null
    	while(l1!==null&&l2!=null&&l2.next!=null){
			if(l1==l2) return true;
			l1 = l1.next;
			l2 = l2.next.next;
		}
		return false;
    }
  }