LeetCode-Easy刷题(32) Linked List Cycle

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sqh201030412/article/details/78679851

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

Follow up:
Can you solve it without using extra space?


给定一个链表,确定它是否有一个循环。  你能在不使用额外空间的情况下解决它吗?



 //两个速度指针
    public boolean hasCycle(ListNode head) {

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

           walker = walker.next;
           runner = runner.next.next;
           if(walker == runner){
               return true;
           }
       }
       return false;
    }


猜你喜欢

转载自blog.csdn.net/sqh201030412/article/details/78679851