leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

linked-list-cycle.js (980B)


      1 //Find if a linked list contains a refrence to another node in the list.
      2 //This would create a circular refrence thus it would have no end.
      3 //To find this I created a set and then for each node checked to see
      4 //if it existed in the set. If it does exist in the set then the list is
      5 //circular because that would mean a refrence to another node is used multiple times
      6 //in the list. The time complexity of this is O(n) because I used a set which
      7 //has constant time searching.
      8 //Time: 71ms Beats: 69.27%
      9 //Memory: 46.3MB Beats: 5.82%
     10 
     11 /**
     12  * Definition for singly-linked list.
     13  * function ListNode(val) {
     14  *     this.val = val;
     15  *     this.next = null;
     16  * }
     17  */
     18 
     19 /**
     20  * @param {ListNode} head
     21  * @return {boolean}
     22  */
     23 var hasCycle = function(head) {
     24     let node_map = new Set();
     25     while(head != null){
     26         if(node_map.has(head)){
     27             return true;
     28         }
     29         else{
     30             node_map.add(head);
     31         }
     32         head = head.next;
     33     }
     34     return false;
     35 };