环形链表问题

  1. 环形链表

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head==null)return false;
        ListNode p1=head;
        ListNode p2=head;
        do{
            p1=p1.next;
            if(p2==null||p2.next==null)return false;
            p2=p2.next.next;
        }while(p1!=p2);
        return true;
    }
}
  1. 环形链表 II

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head==null||head.next==null)return null;
        ListNode slow=head;
        ListNode fast=head;//这个初始化有影响?有的。要从首节点开始。
        do{//这里改成while(slow!=fast)的话就不会进入这个循环了
            slow=slow.next;
            if(fast==null||fast.next==null)return null;
            fast=fast.next.next;
        }while(slow!=fast);

        fast=head;
        while(slow!=fast){
            slow=slow.next;
            fast=fast.next;
        }
        return fast;
    }
}

环形链表问题

上一篇:从零开始学android


下一篇:用window.URL全局对象