w3resource

JavaScript Exercises: Convert a Singly Linked list into an array

JavaScript Singly Linked List: Exercise-15 with Solution

Write a JavaScript program to convert a Singly Linked list into an array and returns it.

Sample Solution:

JavaScript Code:

class Node {
    constructor(data) {
        this.data = data
        this.next = null                
    }
}
class SinglyLinkedList {
    constructor(Head = null) {
        this.Head = Head
    }
add(newNode){
    let node = this.Head;
    if(node==null){
        this.Head = newNode;
        return;
    }
    while (node.next) {
        node = node.next;
    }
    node.next = newNode;
}
  
to_array() {
    let current = this.Head;
    let arr = [];
    while (current) {
        arr.push(current.data);
        current = current.next;
    }
    return arr;
}  
 displayList(){
    let node = this.Head;
    var str = ""
    while (node) {
        str += node.data + "->";
        node = node.next;
    }
    str += "NULL"
    console.log(str);  
  }
}
let numList = new SinglyLinkedList();
numList.add(new Node(12));
numList.add(new Node(13));
numList.add(new Node(14));
numList.add(new Node(15));
numList.add(new Node(14));
console.log("Singly Linked list:")
numList.displayList();
console.log("Converts the said Singly Linked Lists into an array");
result = numList.to_array();
console.log(result);
let numList1 = new SinglyLinkedList();
console.log("New Singly Linked list:")
numList1.displayList();
console.log("Converts the said Singly Linked Lists into an array");
result = numList1.to_array();
console.log(result);

Sample Output:

Singly Linked list:
12->13->14->15->14->NULL
Converts the said Singly Linked Lists into an array
[12,13,14,15,14]
New Singly Linked list:
NULL
Converts the said Singly Linked Lists into an array
[]

Flowchart:

Flowchart: JavaScript Exercises: Convert a Singly Linked list into an array.

Live Demo:

See the Pen javascript-singly-linked-list-exercise-15 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Singly Linked List Previous: Remove the tail element from a Singly Linked list.
Singly Linked List Next: Convert a Singly Linked list into a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

Using map with async Functions

The array instance map method can be used with the Promise.all to return a promise with an array of items mapped to a promise.
For instance, we can write:

const getData = async () => {
  return Promise.all(arr.map(item => asyncFunc(item)))
}

Assuming that asyncFunc is a function that returns a promise, we return an array of promises with the map call.
Therefore, we can use Promise.all on it so that we can invoke them in parallel.

Ref: https://bit.ly/3mp5NgH