141. Linked List Cycle

来源:互联网 发布:手机指南针软件 编辑:程序博客网 时间:2024/05/16 18:57

判断是否为循环链表。使用快慢指针,p1=p1.next , p2=p2.next.next  如果为循环链表,p2会追上p1.

Given a linked list, determine if it has a cycle in it.

public class Solution {

    public boolean hasCycle(ListNode head) {
        if(head==null)
    return false;
        ListNode p1=head;
        if(head.next==null)
            return false;
        ListNode p2=head;
        p1=p1.next;
        p2=p2.next.next;
        while(p1!=null&&p2!=null){
            p1=p1.next;
            if(p2.next==null)
            return false;
            else
            p2=p2.next.next;
            if(p1.equals(p2))
            return true;
        }
   
    return false;
    }
}
0 0
原创粉丝点击