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
Implement a function that reverses a singly linked list in one pass of the list. The...
Implement a function that reverses a singly linked list in one pass of the list. The function accepts a pointer to the beginning of the list and returns a pointer to the beginning of the reversed list. The function must not create any new nodes. Be sure to test your function! You may start with code that you have written for other labs. This is a common interview question!
Implement a function that detects if there is a “loop” in a singly linked list. A...
Implement a function that detects if there is a “loop” in a singly linked list. A “loop” is defined as a link from one node to itself or to another node that is before the node in the list. The function may only make one pass through the list. It must return 1 if a “loop” exists; 0 otherwise. Be sure to test your function! You may start with code that you have written for other labs. This is a...
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...
#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 <<...
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...
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....
You can complete this assignment individually or as a group of two people. In this assignment...
You can complete this assignment individually or as a group of two people. In this assignment you will create a ​​Sorted Singly-Linked List​ that performs basic list operations using C++. This linked list should not allow duplicate elements. Elements of the list should be of type ‘ItemType’. ‘ItemType’ class should have a private integer variable with the name ‘value’. Elements in the linked list should be sorted in the ascending order according to this ‘value’ variable. You should create a...
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...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT
Active Questions
  • The provided file has syntax and/or logical errors. Determine the problem and fix the program. using...
    asked 2 minutes ago
  • What new items will you need to replace a failing processor? Select all that apply.   ...
    asked 21 minutes ago
  • A system is to be developed for an airport. When passengers have boarded an aircraft, a...
    asked 29 minutes ago
  • After reading Module 5 PowerPoint 1 - The Philosophy of Human Existance and Health Care Policy,...
    asked 37 minutes ago
  • 1. Do you feel play has a place in supporting literacy development in early childhood? Explain...
    asked 41 minutes ago
  • How should roles be selected for the Emergency Operations Center (EOC)?  Is seniority less important than experience?...
    asked 54 minutes ago
  • Discuss routing issues and solutions namely, count-to-infinity, split horizon, split horizon with poison reverse, and hold-down...
    asked 54 minutes ago
  • Find an optimal parenthesization of a matrix-chain product whose sequence of dimensions is〈5,10,3,12,5,50,6〉.
    asked 1 hour ago
  • Water at 60 F (density=62.4lbm/ft^3 and dynamic viscosity = 7.5x10^-4 lbm/ft-s) is to be pumped through...
    asked 1 hour ago
  • ibuprofen an aspirin substitute has the following percent composition C, 75.69%; H,8.80%; O,15.51%. determine the empirical...
    asked 1 hour ago
  • Describe in brief some of the aspects of understanding words in the study of language
    asked 1 hour ago
  • Anticipated sales for Safety Grip Company were 75,000 passenger car tires and 23,000 truck tires. Rubber...
    asked 1 hour ago