[Testdome] Song

whitehousechef·2023년 12월 5일

never thought an easy labelled question needs to think of floyd cycle

we first initialise slow and fast pointer to the current Song instance (node) via Song slow = this;

Then, we use a while loop to check if there is indeed a value after fast pointer's nextSong or fast pointer is not pointing to a null value. In that loop, we hop slow once and hop fast twice.

If there indeeed is a cycle, there will come a point where slow==fast or else the while condition loop will be met and we will end trhe recursion cuz both fast pointer or fast pointer.nextSong will be null (i.e. end of linked list). If there is a cyle it will not be null cuz it will link to the start of the list or to some node of the list if it reaches the end.

function hasCycle(head):
    // Initialization
    slow = head
    fast = head
    
    // Traversal and Cycle Detection
    while fast is not null and fast.next is not null:
        slow = slow.next
        fast = fast.next.next
        
        // Cycle Detection
        if slow == fast:
            return true  // Cycle detected
    
    // No cycle found
    return false
    public boolean isInRepeatingPlaylist() {
        Song slow=this;
        Song fast=this;
        if (slow == null || slow.nextSong == null) return false;
        while(fast!=null && fast.nextSong!=null){
            slow=slow.nextSong;
            fast=fast.nextSong.nextSong;
            if(slow==fast){
                return true;
            }
        } 
        return false;
        
    }

0개의 댓글