Skip to content

Instantly share code, notes, and snippets.

@hiroshi-maybe
Created February 19, 2013 10:38
Show Gist options
  • Save hiroshi-maybe/4984753 to your computer and use it in GitHub Desktop.
Save hiroshi-maybe/4984753 to your computer and use it in GitHub Desktop.
Detect circular reference of linked list in Javascript.
/*
* circular-reference-detect.js
* author: Hiroshi Kori
*
* Detect circular reference of linked list
*
* 1) Overview
* - Reverse linked-list until finding a node whose next pointer is null.
* - Chekck the head node if its next pointer is null
* 1) null: the node is not traversed twice. (no circular reference)
* 2) otherwise: traversed twice because of circulation. (circular reference)
*
* 2) Usage Example
*
* var head={val:"head"},n1={val:"1"},n2={val:"2"},n3={val:"3"},n4={val:"4"};
*
* var cir_linked_list_helper = function(head) {
* head.next=n2,n2.next=n4,n4.next=n3,n3.next=n1,n1.next=n4;
* return head;
* };
* var non_cir_linked_list_helper = function(head) {
* head.next=n2,n2.next=n4,n4.next=n3,n3.next=n1;
* return head;
* };
*
* head=cir_linked_list_helper(head);
* console.log(is_circular(head));
*
*/
var is_circular = (function() {
var reverse = function(head){
var current=head,next=null,prev=null;
while(current.next!=null && current.next!=undefined) {
next=current.next;
current.next=prev;
prev=current;
current=next;
}
current.next=prev;
return current;
};
return function(head){
var tested=head.next;
reverse(tested);
return tested.next!==null;
};
})(head);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment