带环链表
给定一个链表,判断它是否有环。
解题
定义两个指针p1 p2
p1每次向前走一步
p2每次向前走两步
当p2能赶上p1的时候说明有环
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The first node of linked list. * @return: True if it has a cycle, or false */ public boolean hasCycle(ListNode head) { // write your code here if(head == null || head.next == null) return false; ListNode p1 = head; ListNode p2 = head; p2 = p2.next; while(p2.next!=null && p2.next.next!=null){ if(p1 == p2){ return true; } p1 = p1.next; p2 = p2.next.next; } return false; } }