Check Cyclic LinkedList – I

Approach 1

Where we are using Temp pointer.

/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/

/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycl…


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by ZeeshanAli-0704

Approach 1

Where we are using Temp pointer.

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {

    let tempNode = new ListNode(0);
    let current = head;

    while(current){
        if(current.next === tempNode){
            return true;
        }
        let saveNext = current.next;
        current.next = tempNode;
        current = saveNext;
    }
    return false;
};

Approach 2

Using Map (or can be done using set) to keep track of visited pointers

var hasCycle = function(head) {
    let mapValues = new Map();
    while (head) {
        if (mapValues.has(head)) {
            return true;
        } else {
            mapValues.set(head, "Yes");
            head = head.next;
        }
    }

    return false;

};

Approach 3

Where you can modify the way of creating Node by using additional pointer -(Visited = false(default)) & can traverse list.
if visited is true -> return true else false


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by ZeeshanAli-0704


Print Share Comment Cite Upload Translate Updates
APA

ZeeshanAli-0704 | Sciencx (2022-09-07T02:55:12+00:00) Check Cyclic LinkedList – I. Retrieved from https://www.scien.cx/2022/09/07/check-cyclic-linkedlist-i/

MLA
" » Check Cyclic LinkedList – I." ZeeshanAli-0704 | Sciencx - Wednesday September 7, 2022, https://www.scien.cx/2022/09/07/check-cyclic-linkedlist-i/
HARVARD
ZeeshanAli-0704 | Sciencx Wednesday September 7, 2022 » Check Cyclic LinkedList – I., viewed ,<https://www.scien.cx/2022/09/07/check-cyclic-linkedlist-i/>
VANCOUVER
ZeeshanAli-0704 | Sciencx - » Check Cyclic LinkedList – I. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/09/07/check-cyclic-linkedlist-i/
CHICAGO
" » Check Cyclic LinkedList – I." ZeeshanAli-0704 | Sciencx - Accessed . https://www.scien.cx/2022/09/07/check-cyclic-linkedlist-i/
IEEE
" » Check Cyclic LinkedList – I." ZeeshanAli-0704 | Sciencx [Online]. Available: https://www.scien.cx/2022/09/07/check-cyclic-linkedlist-i/. [Accessed: ]
rf:citation
» Check Cyclic LinkedList – I | ZeeshanAli-0704 | Sciencx | https://www.scien.cx/2022/09/07/check-cyclic-linkedlist-i/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.