Print the Elements of a Linked List

  • + 0 comments
    function printLinkedList(head) {
        let current = head;
        while (current !== null) {
            console.log(current.data);
            current = current.next;
        }
    }
    

    Here, we have a function printLinkedList that takes in a reference to the head of the linked list. We initialize a variable current to the head of the list. Then we loop through the list using a while loop until current becomes null (which means we've reached the end of the list). Within the loop, we print the data of the current node using console.log(current.data) and update the current variable to point to the next node in the list using current = current.next.

    Note that we assume that the linked list is implemented using nodes with data and next properties, where data stores the value of the node and next points to the next node in the list.