w3resource

JavaScript Exercises: Convert a Singly Linked list into a string

JavaScript Singly Linked List: Exercise-16 with Solution

Write a JavaScript program to convert a Singly Linked list into a string 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_string() {
    let current = this.Head;
    let str = "";
    while (current) {
        str += current.data + " ";
        current = current.next;
    }
    return str;
}
 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 a string:");
result = numList.to_string();
console.log(result);
let numList1 = new SinglyLinkedList();
console.log("New Singly Linked list:")
numList1.displayList();
console.log("Converts the said Singly Linked Lists into a string:");
result = numList1.to_string();
console.log(result);

Sample Output:

"Singly Linked list:"
"12->13->14->15->14->NULL"
"Converts the said Singly Linked Lists into a string:"
"12 13 14 15 14 "
"New Singly Linked list:"
"NULL"
"Converts the said Singly Linked Lists into a string:"
""

Flowchart:

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

Live Demo:

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


Improve this sample solution and post your code through Disqus

Singly Linked List Previous: Convert a Singly Linked list into an array.
Singly Linked List Next: Get index of an given element in a Singly Linked list.

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