原题链接在这里:https://leetcode.com/problems/linked-list-cycle/
题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题解:
快慢指针,一快runner, 每次走两步. 一慢walker, 每次走一步,若是它俩相遇就是有cycle.
Time Complexity: O(n). Space: O(1).
AC Java:
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 }
AC JavaScript:
1 /** 2 * Definition for singly-linked list. 3 * function ListNode(val) { 4 * this.val = val; 5 * this.next = null; 6 * } 7 */ 8 9 /** 10 * @param {ListNode} head 11 * @return {boolean} 12 */ 13 var hasCycle = function(head) { 14 if(!head || !head.next){ 15 return false; 16 } 17 18 var walker = head; 19 var runner = head; 20 while(runner && runner.next){ 21 walker = walker.next; 22 runner = runner.next.next; 23 if(walker === runner){ 24 return true; 25 } 26 } 27 28 return false; 29 };