Leetcode-141linked-list-cycle(环形链表)

先看一下题目描述:

Leetcode-141linked-list-cycle(环形链表)_第1张图片

判断一个链表是否有环,直接上代码;

  public boolean hasCycle(ListNode head) {
        if(head==null)return false;
        ListNode walker = head;
        ListNode runner = head;
        while(runner.next!=null&&runner.next.next!=null){
            walker = walker.next;
            runner = runner.next.next;
            if(walker==runner)return true;
        }
        return false;
    }

 

你可能感兴趣的:(leetcode,链表)