带环链表

给定一个链表,判断它是否有环。

解题

定义两个指针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;
    }
}
Java Code

相关文章:

  • 2021-07-03
  • 2021-11-29
  • 2021-10-06
  • 2022-12-23
  • 2021-07-14
  • 2021-12-22
  • 2021-09-30
  • 2021-08-09
猜你喜欢
  • 2021-11-05
  • 2021-09-04
  • 2021-06-08
  • 2021-12-12
  • 2021-11-20
  • 2021-08-14
  • 2021-05-26
相关资源
相似解决方案