[LeetCode][JavaScript]Linked List Cycle

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?

https://leetcode.com/problems/linked-list-cycle/

 

 


 

 

判断链表是否有环。

先是用了额外空间的做法。

移出每个访问过的节点,指向头节点,如果遇到了指向头节点的点,说明有环。

 1 /**
 2  * @param {ListNode} head
 3  * @return {boolean}
 4  */
 5 var hasCycle = function(head) {
 6     var h = new ListNode("head");
 7     if(!head){
 8         return false;
 9     }
10     if(head.next && head.next == head){
11         return true;
12     }
13     return cycle(head);
14 
15     function cycle(node){
16         if(node === null || node.next === null){
17             return false;
18         }else if(node.next.val === h.val){
19             return true;
20         }else{
21             var tmp = node.next;
22             node.next = h;
23             return cycle(tmp);
24         }
25     }
26 };

 

不用额外空间:

https://leetcode.com/discuss/1566/by-saying-using-no-extra-space-does-it-mean-o-0-in-space

使用快慢指针,如果重合则说明有环。

 1 /**
 2  * @param {ListNode} head
 3  * @return {boolean}
 4  */
 5 var hasCycle = function(head) {
 6     var slow = head, fast = head;
 7     while(true){
 8         if(fast === null || fast.next === null){
 9             return false;
10         }
11         slow = slow.next;        
12         fast = fast.next.next;
13         if(slow === fast){
14             return true;
15         }
16     }
17 };

 

 

posted @ 2015-08-30 21:14  `Liok  阅读(404)  评论(0编辑  收藏  举报