原題連接在這裏:https://leetcode.com/problems/linked-list-cycle/html
題目:oop
Given a linked list, determine if it has a cycle in it.post
Follow up:
Can you solve it without using extra space?url
題解:spa
快慢指針,一快runner, 每次走兩步. 一慢walker, 每次走一步,如果它倆相遇就是有cycle.指針
Time Complexity: O(n). Space: O(1).code
AC Java:htm
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public boolean hasCycle(ListNode head) { 14 if(head == null || head.next == null){ 15 return false; 16 } 17 ListNode walker = head; 18 ListNode runner = head; 19 while(runner.next != null && runner.next.next != null){ 20 walker = walker.next; 21 runner = runner.next.next; 22 if(walker == runner){ 23 return true; 24 } 25 } 26 return false; 27 } 28 }