LeetCode-Easy刷題(32) Linked List Cycle
阿新 • • 發佈:2018-12-04
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; }