题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
思路:双指针,p1每次移动1个结点;p2每次移动2个结点。 (一个for循环解决)
public class Solution {
public boolean hasCycle(ListNode head) {
//for循环
for (ListNode p1 = head, p2 = head; p1!=null && p2!=null && p1.next!=null && p2.next!=null; p1 = p1.next, p2 = (p2.next).next) {
if (p1.next==(p2.next).next)
return true;
}
return false;
}
}