Question

Singly Linked List In Javascript - How to implement when given functions and tests to pass...

Singly Linked List In Javascript - How to implement when given functions and tests to pass

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

So I am trying to implement a singly linked list that given the below function will pass the bottom four tests when ran in Node.js with the 'runTests()' command.

Please help me generate the singly linked list that will work and pass the tests at the bottom. 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 by calling the 'runTests()' command to run the given tests.Thank you!

//--------------------------------

//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 IMPLEMENTATION WOULD BE HERE (NEEDS 'Cons', 'Nils', and 'List" to be declared

//-------------------------------

//--------------------------------

//TESTS THE LIST SHOULD PASS (Run Program with Node.js, Load it and use command 'runTests()' to test these

//--------------------------------

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()

//-------------------------------------

//IMPORTANT TO NOTE

//-------------------------------------

// singly-linked list.  Lists are constructed with two kinds of objects:
// - A `Cons` object represents a non-empty list.  It holds a single
//   element of the list, along with the rest of the list.
// - A `Nil` object represents an empty list, containing no elements,
//   and no other elements.
// These objects are not wrapped around anything; if you take a list,
// you take `Cons` or `Nil` objects.

Homework Answers

Answer #1

Here i am writing a code for singly linked list. You can edit code according to your need.

// User defined class node
class Node {
   // constructor
   constructor(element)
   {
       this.element = element;
       this.next = null
   }
}

// linkedlist class
class LinkedList {
   constructor()
   {
       this.head = null;
       this.size = 0;
   }

   // functions to be implemented
   // add(element)
   // insertAt(element, location)
   // removeFrom(location)

   // Helper Methods-


   // size_Of_List
   // PrintList

}

1. add(element)=>

// adds an element at the end
// of list
add(element)
{
   // creates a new node
   var node = new Node(element);

   // to store current node
   var current;

   // if list is Empty add the
   // element and make it head
   if (this.head == null)
       this.head = node;
   else {
       current = this.head;

       // iterate to the end of the
       // list
       while (current.next) {
           current = current.next;
       }

       // add node
       current.next = node;
   }
   this.size++;
}

2. insertAt(element, index)

// insert element at the position index
// of the list
insertAt(element, index)
{
   if (index > 0 && index > this.size)
       return false;
   else {
       // creates a new node
       var node = new Node(element);
       var curr, prev;

       curr = this.head;

       // add the element to the
       // first index
       if (index == 0) {
           node.next = head;
           this.head = node;
       } else {
           curr = this.head;
           var it = 0;

           // iterate over the list to find
           // the position to insert
           while (it < index) {
               it++;
               prev = curr;
               curr = curr.next;
           }

           // adding an element
           node.next = curr;
           prev.next = node;
       }
       this.size++;
   }
}

3.removeFrom(index)=>

// removes an element from the
// specified location
removeFrom(index)
{
   if (index > 0 && index > this.size)
       return -1;
   else {
       var curr, prev, it = 0;
       curr = this.head;
       prev = curr;

       // deleting first element
       if (index == = 0) {
           this.head = curr.next;
       } else {
           // iterate over the list to the
           // position to removce an element
           while (it < index) {
               it++;
               prev = curr;
               curr = curr.next;
           }

           // remove the element
           prev.next = curr.next;
       }
       this.size--;

       // return the remove element
       return curr.element;
   }
}

4. size_of_list()

// gives the size of the list
size_of_list()
{
   console.log(this.size);
}

5. printList()

// prints the list items
printList()
{
   var curr = this.head;
   var str = "";
   while (curr) {
       str += curr.element + " ";
       curr = curr.next;
   }
   console.log(str);
}

Know the answer?
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
Similar Questions
JAVA Implement a θ(n) time non-recursive program that reverses a singly linked list L of n...
JAVA Implement a θ(n) time non-recursive program that reverses a singly linked list L of n elements. The program gets the head of the list (L.head) as input and cannot use any storage other than the given list. Don't not use recursive~~~~~~~ thanks
1. Design and implement a CircularLinkedList, which is essentially a linked list in which the next...
1. Design and implement a CircularLinkedList, which is essentially a linked list in which the next reference of the tail node is set to refer back to the head of the list (rather than null) . Start from the SinglyLinkedList provided in the Lecture (not the built-in Java LinkedList class). 2. Starting from  SinglyLinkedList you will need to modify or complete methods: first(), last(), addFirst(), addLast(), removeFirst(), toString(), and also create a new rotate() method which will move the tail to...
IN JAVA Language- Singly Linked List Implementation Implement a Linked List in your language. Use your...
IN JAVA Language- Singly Linked List Implementation Implement a Linked List in your language. Use your Can class. You need to create a driver that makes several Can objects and places them in alphabetical order in a list. Identify the necessary methods in a List Linked implementation. Look at previous Data Structures (stack or queue) and be sure to include all necessary methods. NOT USE your language's Library List . You will receive zero points. Write a LinkedList class. Include...
#Linked Lists and Classes #C++ Hi, please use singly linked list method to do this question....
#Linked Lists and Classes #C++ Hi, please use singly linked list method to do this question. Thank you! Here’s the contents of a file called example.cpp: // example.cpp #include "LinkedList.h" #include <iostream> #include <string> using namespace std; int main() { cout << "Please enter some words (ctrl-d to stop):\n"; LinkedList lst; int count = 0; string s; while (cin >> s) { count++; lst.add(remove_non_letters(s)); } // while cout << "\n" << count << " total words read in\n"; cout <<...
Implement a singly linked list having all unique elements with the following operations.I 0 x –...
Implement a singly linked list having all unique elements with the following operations.I 0 x – Inserts element x at the end. I 1 y x – If the element y exists, then insert element x after the element y, else insert element y before the existing element x. Assuming either the element x or the element y exists. I 2 z y x – Inserts element x in the middle of the elements z and y. The element z...
The language is Java. Using a singly-linked list, implement the four queue methods enqueue(), dequeue(), peek(),...
The language is Java. Using a singly-linked list, implement the four queue methods enqueue(), dequeue(), peek(), and isEmpty(). For this assignment, enqueue() will be implemented in an unusual manner. That is, in the version of enqueue() we will use, if the element being processed is already in the queue then the element will not be enqueued and the equivalent element already in the queue will be placed at the end of the queue. Additionally, you must implement a circular queue....
Create a C++ project. Download and add the attached .h and .cpp to the project. Write...
Create a C++ project. Download and add the attached .h and .cpp to the project. Write an implementation file to implement the namespace declared in the attached CSCI361Proj5.h. Name the implementation file as YourNameProj5.cpp and add it to the project. Run the project to see your grade. .h file: // Provided by: ____________(your name here)__________ // Email Address: ____________(your email address here)________ // FILE: link.h // PROVIDES: A toolkit of 14 functions for manipulating linked lists. Each // node of...
Please create a python module named homework.py and implement the functions outlined below. Below you will...
Please create a python module named homework.py and implement the functions outlined below. Below you will find an explanation for each function you need to implement. When you are done please upload the file homework.py to Grader Than. Please get started as soon as possible on this assignment. This assignment has many problems, it may take you longer than normal to complete this assignment. This assignment is supposed to test you on your understanding of reading and writing to a...
Implement the following functions in the given code: def random_suit_number(): def get_card_suit_string_from_number(n): def random_value_number(): def get_card_value_string_from_number(n):...
Implement the following functions in the given code: def random_suit_number(): def get_card_suit_string_from_number(n): def random_value_number(): def get_card_value_string_from_number(n): def is_leap_year(year): def get_letter_grade_version_1(x): def get_letter_grade_version_2(x): def get_letter_grade_version_3(x): Pay careful attention to the three different versions of the number-grade-to-letter-grade functions. Their behaviors are subtly different. Use the function descriptions provided in the code to replace the pass keyword with the necessary code. Remember: Parameters contain values that are passed in by the caller. You will need to make use of the parameters that each...
ALL CODE MUST BE IN C++ Before you begin, you must write yourself a LinkedList class...
ALL CODE MUST BE IN C++ Before you begin, you must write yourself a LinkedList class and a Node class (please name your classes exactly ​as I did here). Please follow the below specifications for the two classes. Node.cpp ● This must be a generic class. ● Should contain a generic member variable that holds the nodes value. ● Should contain a next and prev Node* as denoted here. ● All member variables should be private. ● Use public and...