Question

IMPLEMENT AN IMMUTABLE SINGLY LINKED LIST IN JAVASCRIPT ------------------------------------------------------------------------------------------------------------------------- So I am trying to implement a...

IMPLEMENT AN IMMUTABLE SINGLY LINKED LIST IN JAVASCRIPT

-------------------------------------------------------------------------------------------------------------------------

So I am trying to implement a singly linked list that given the below function will pass the bottom four tests when ran.

Please help me generate the singly linked list that will work and pass the tests. I will only use this as a reference so please add comments to explain what you are doing so I can understand and write this myself. I think a join method may need to be used in the linked list section but i'm not sure.

I am currently using node.js to run and test this code and called 'runTests()' to test it.

--------------------------------

FUNCTION

--------------------------------

function join(list, delim) {
var retval = "[";
while (list instanceof Cons &&
!(list.tail() instanceof Nil)) {
retval += list.head().toString() + delim;
list = list.tail();
}
if (list instanceof Cons) {
retval += list.head().toString();
}
retval += "]";
return retval;
} // join

___________________

LINKED LIST WOULD BE HERE TECHNICALLY

-------------------------------

--------------------------------

TESTS THE LIST SHOULD PASS

--------------------------------

function runTest(test) {
process.stdout.write(test.name + ": ");
try {
test();
process.stdout.write("pass\n");
} catch (error) {
process.stdout.write("FAIL\n");
console.log(error);
}
} // runTest
  
function assertEquals(expected, received) {
if (expected !== received) {
throw ("\tExpected: " + expected.toString() + "\n" +
"\tReceived: " + received.toString());
}
} // assertEquals

function test_nil_join() {
let nil = new Nil();
assertEquals("[]",
nil.join(", "));
} // test_nil_join

function test_nil_toString() {
let nil = new Nil();
assertEquals("[]",
nil.toString());
} // test_nil_toString

function runTests() {
// ---begin tests for nil---

// instanceof
runTest(test_nil_instanceof_list);

// join
runTest(test_nil_join);

// toString
runTest(test_nil_toString);

} //runTests()

0 0
Add a comment Improve this question Transcribed image text
Answer #1
class Node{
    constructor(data, next = null){
        this.data = data,
        this.next = next
    }
}

// In the above code, a Node class is defined. When an instance of the Node class is formed, the constructor function will be called to initialize the object with two properties, data and a pointer named next. The pointer next is initialized with a default value of null, incase no value is passed as an argument.

class LinkedList{
    constructor(){
        this.head = null;
    }
        
        insertAtBeginning = (data) => {
                // A newNode object is created with property data and next = null
                let newNode = new Node(data);
                // The pointer next is assigned head pointer so that both pointers now point at the same node.
                newNode.next = this.head;
                // As we are inserting at the beginning the head pointer needs to now point at the newNode. 
    
                this.head = newNode;
                return this.head;
        }
        
        insertAtEnd = (data) => {
                // A newNode object is created with property data and next=null
    
                let newNode = new Node(data);
                // When head = null i.e. the list is empty, then head itself will point to the newNode.
                if(!this.head){
                        this.head = newNode;
                        return this.head;
                }
                // Else, traverse the list to find the tail (the tail node will initially be pointing at null), and update the tail's next pointer.
                let tail = this.head;
                while(tail.next !== null){
                        tail = tail.next;
                }
                tail.next = newNode;
                return this.head;
        }
        
        // A helper function getAt() is defined to get to the desired position. This function can also be later used for performing delete operation from a given position.
    getAt = (index) => {
        let counter = 0;
        let node = this.head;
        while (node) {
            if (counter === index) {
               return node;
            }
            counter++;
            node = node.next;
        }
        return null;
    }
        
        // The insertAt() function contains the steps to insert a node at a given index.
    insertAt = (data, index) => {
                // if the list is empty i.e. head = null
                if (!this.head) {
                        this.head = new Node(data);
                        return;
        }
                // if new node needs to be inserted at the front of the list i.e. before the head. 
        if (index === 0) {
                        this.head = new Node(data, this.head);
                        return;
        }
                // else, use getAt() to find the previous node.
                const previous = this.getAt(index - 1);
        let newNode = new Node(data);
        newNode.next = previous.next;
        previous.next = newNode;       

        return this.head
        }
        
        
        deleteFirstNode = () => {
                if(!this.head){
                        return;
                }
                this.head = this.head.next;
                return this.head;
        }
        
        deleteLastNode = () => {
                if(!this.head){
                        return null;
                }
                // if only one node in the list
                if(!this.head.next){
                        this.head = null;
                        return;
                }
                let previous = this.head;
                let tail = this.head.next;
   
                while(tail.next !== null){
                        previous = tail;
                        tail = tail.next;
                }
   
                previous.next = null;
                return this.head;
        }
        
        deleteAt = (index) => {
                // when list is empty i.e. head = null
                if (!this.head) {
                        this.head = new Node(data);
                        return;
                }
                // node needs to be deleted from the front of the list i.e. before the head.
                if (index === 0) {
                        this.head = this.head.next;
                        return;
                }
                // else, use getAt() to find the previous node.
                const previous = this.getAt(index - 1);
    
                if (!previous || !previous.next) {
                        return;
                }
    
                previous.next = previous.next.next;     
                return this.head
        }
        
        // Delete the complete linked list
        deleteList = () => {
                this.head = null;
        }
        
}


// A list object is created with a property head, currently pointing at null

let list = new LinkedList();

// Insert xyz as data in the beginning of the list
list.insertAtBeginning('xyz');

// Use the remaining functions the same way :)
Add a comment
Know the answer?
Add Answer to:
IMPLEMENT AN IMMUTABLE SINGLY LINKED LIST IN JAVASCRIPT ------------------------------------------------------------------------------------------------------------------------- So I am trying to implement a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Currently I am learning about set theory. I am trying to implement a set using a hashtable with singly linked lists. I a...

    Currently I am learning about set theory. I am trying to implement a set using a hashtable with singly linked lists. I am very confused as to where I should start, as many of the online resources reference basically hash table implementations. How would I go about a template to implement the very basic structures needed for the set in C? Just confused as to where to start. Currently this is my current structure: typedef struct s_entry t char *key...

  • ^^^ Q3. I am trying to implement double linked list but I was failed to write...

    ^^^ Q3. I am trying to implement double linked list but I was failed to write the code so anyone gives the main Code in the main function   THANK YOU FOR ADVANCE #include<stdio.h> #include<stdlib.h> #include<alloc.h> struct node {      int info;      struct node *lptr,*rptr; }; typedef struct node DL; DL *delete( ) , *insert ( ); void display(); DL *delete(DL *start,int x) {      DL *left,*right,*curr;      curr = start;      if( start == NULL)       {                 printf("\nDoubly...

  • Given a singly-linked list interface and linked list node class, implement the singly-linked list which has...

    Given a singly-linked list interface and linked list node class, implement the singly-linked list which has the following methods in Java: 1. Implement 3 add() methods. One will add to the front (must be O(1)), one will add to the back (must be O(1)), and one will add anywhere in the list according to given index (must be O(1) for index 0 and O(n) for all other indices). They are: void addAtIndex(int index, T data), void addToFront(T data), void addToBack(T...

  • Part 1: Implement a singly linked list -------------------------------------- (a) Your job is to implement a generic...

    Part 1: Implement a singly linked list -------------------------------------- (a) Your job is to implement a generic singly linked list that can hold any data type. The interface has been specified and provided to you in a header file called mylist.h. So your job is to write mylist.c that implements each function whose prototype is included in mylist.h. Specifically, you are asked to write the following functions: struct Node *addFront(struct List *list, void *data) void traverseList(struct List *list, void (*f)(void *))...

  • I am trying to make a linked list queue and I am trying to use the...

    I am trying to make a linked list queue and I am trying to use the display method I made just to see if its working but when I run it nothing is displayed please help. Also the newPlane boolean was made just so I can randomly decide if the plane is going to join the queue or not. public class PlaneSimulation { public static void main(String[] args) { int landTime = 2; int takeoffTime = 3; int avgArrivalInterval =...

  • BELOW IS THE CODE I ALREADY HAVE Linked List - Delete Modify Lab 5 and include...

    BELOW IS THE CODE I ALREADY HAVE Linked List - Delete Modify Lab 5 and include the method to delete a node from the Linked List. In summary: 1) Add the method Delete 2) Method call to delete, with a number that IS in the list 3) Method call to delete, with a number that is NOT in the list - Be sure to include comments - Use meaningful identifier names (constants where appropriate) import java.io.*; 1/ Java program to...

  • Programming in C: I am trying to modify this linked list to be doubly linked list....

    Programming in C: I am trying to modify this linked list to be doubly linked list. I’m also trying to add a print in reverse function. I’m really struggling with how to change the insert function to doubly link the nodes without effecting the alphabetical sorting mechanism. Example of desired output: Enter your choice: 1 to insert an element into the list. 2 to delete an element from the list. 3 to end. ? 1 Enter a character: a The...

  • 8.9 Coding lab #5: create a dynamic array ADT and a singly linked list ADT. Honor Code...

    8.9 Coding lab #5: create a dynamic array ADT and a singly linked list ADT. Honor Code Your answers to this homework must be your own work.You are not allowed to share your solutions.You may not engage in any other activities that will dishonestly improve your results or dishonestly improve or damage the results of others. Plagiarism Plagiarism is when you copy words, ideas, or any other materials from another source without giving credit. Plagiarism is unacceptable in any academic environment....

  • The question I want answered is in C++. How can I pass a value to a function and create a new linked list out of it? For example I have: void getIntegerInput(List<int> list) {    int s;    std::...

    The question I want answered is in C++. How can I pass a value to a function and create a new linked list out of it? For example I have: void getIntegerInput(List<int> list) {    int s;    std::cout << "Type a positive integer then click enter to add it to the linked list\n";    std::cout << "Type -1 to stop\nType -2 to delete an item from the list\n";    std::cin >> s;    while (s != -1)    {        if (s == -2) {            int...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT