Question

In: Computer Science

Javascript Problem: List Reverse Given a list: var list = { value: 1, next: { value:...

Javascript Problem: List Reverse

Given a list:

var list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: null     
    }
  }
};

Reverse the order of the list so that it looks like:

var list = {
  value: 3,
  next: {
    value: 2,
    next: {
      value: 1,
      next: null
    }
  }
};

Use the following shell if needed:

//assignment1.js

function reverseList(list) {
    // your code here
    ...
    return reversedList;
}

Example Test Case(s):

Arguments: { value: 1, next: { value: 2, next: { value: 3, next: null } } };
Returns: { value: 3, next: { value: 2, next: { value: 1, next: null } } };

Arguments: { value: "a", next: { value: "b", next: { value: "c", next: null } } };
Returns: { value: "c", next: { value: "b", next: { value: "a", next: null } } };

Requirements:

  • You cannot use the built-in reverse() function.
  • null is non-existent object, you may use an empty object instead if desired.
  • Your function should be able to reverse a list of values of any type.
  • You must use at least one array to solve the problem.

Solutions

Expert Solution

// Javascript program to reverse the order of the list

// function to reverse the order of the input list and return the reversed list
function reverseList(list) {
  
   // create an empty reversedList
   reversedList = {};
  
   // create an empty array to store the elements of the list
   data = [];
  
   // set curr to list i.e start of the list
    curr = list;
  
   // loop that continues till the end of the list i.e until null or empty object is not encountered
   while((curr != null) && (Object.keys(curr).length != 0))
   {
       data.push(curr.value); // insert curr's value at the end of data
       curr = curr.next; // move curr to next node
   }
  
   // set curr to reversedList start pointer
   curr = reversedList;
  
   // loop over the data array in reverse order i.e from last to first
   for(var i=data.length-1;i>=0;i--)
   {
       // reversedList is an empty object
       if(Object.keys(reversedList).length == 0){
           // set reversedList list value to ith element of data and next to null
           reversedList =    {value:data[i], next: null};
           curr = reversedList; // set curr to reversedList
       }  
       else // reversedList is not an empty object
       {  
           // set value and next for node next to curr
           curr.next = {value:data[i], next:null};
           curr = curr.next; // move curr to next node
       }  
   }
  
return reversedList;
}

// test the function
var list = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: null
}
}
};

console.log(reverseList(list));

var list = { value: "a", next: { value: "b", next: { value: "c", next: null } } };
console.log(reverseList(list));

//end of program

Output:


Related Solutions

/*     Here is an example of a conditional in JavaScript */ var numberOfParticipants = 5; var...
/*     Here is an example of a conditional in JavaScript */ var numberOfParticipants = 5; var maxNumberOfParticipants = 10; if (numberOfParticipants < maxNumberOfParticipants) {     console.log("You can add another participant now"); } else {     console.log("Sorry, you have reached the max number of participants and cannot add another"); } /*     Now it's your turn - create a simple conditional like my example. You can setup variables like I did or just use     hard-coded numbers */ /*     Here is an example of creating...
Javascript problem: Given an argument of a list of book objects: Example test case input: {...
Javascript problem: Given an argument of a list of book objects: Example test case input: { "title" : "Book A", "pages": "50", "next": { "title": "Book B", "pages": 20, "next": null } } create a recursive function to return the total number total # of pages read in the list. If there are no books in the list, return 0.
reverse_number_in_list(number_list:list)-> list This function will be given a list of numbers your job is to reverse...
reverse_number_in_list(number_list:list)-> list This function will be given a list of numbers your job is to reverse all the numbers in the list and return a list with the reversed numbers. If a number ends with 0 you need to remove all the trailing zeros before reversing the number. An example of reversing numbers with trailing zeros: 10 -> 1, 590 -> 95. None of the numbers in the number_list will be less than 1. Example: number_list = [13, 45, 690,...
var selectedColor = document.getElementById("colorChoice").value; var selectedStyle = document.getElementById("style").value; var selectedSize = document.getElementById("size").value; var orderMessage = "Your...
var selectedColor = document.getElementById("colorChoice").value; var selectedStyle = document.getElementById("style").value; var selectedSize = document.getElementById("size").value; var orderMessage = "Your order is: Color = " + selectedColor + "; Style = " + selectedStyle + "; Size = " + selectedSize+"\n"; if (selectedStyle==="Long-sleeve") //Add code to calculate the price and concatenate it to the orderMessage //For example, "The order is: Color = gray; Style=T-Shirt; Size = XL \nThe price is $12" //If the style and size are not available, then concatenate the message that...
<script type = "text/javascript">     var  first_number = prompt("Please enter the first number for our sequence calculation");     var  second_number...
<script type = "text/javascript">     var  first_number = prompt("Please enter the first number for our sequence calculation");     var  second_number = prompt("Please enter the second number for our sequence calculation");     first_number = parseInt(first_number);     second_number = parseInt(second_number);     console.log(first_number);     console.log(second_number);     var previous_number = first_number;     var next_number = second_number;     var count = 10;     while(count>0)     {         count = count - 1;         var new_number = previous_number + next_number;         previous_number = next_number;         next_number = new_number;         console.log(next_number)     } I need to use the fib function to print the same number sequence...
Illustrate the difference between the value-at-risk (VaR) and conditional value-at-risk (C-VaR) measures
Illustrate the difference between the value-at-risk (VaR) and conditional value-at-risk (C-VaR) measures
Part 1 Here is some code: def foo(var): var = [] var.append("hello") var.append("world") list = ["bah"]...
Part 1 Here is some code: def foo(var): var = [] var.append("hello") var.append("world") list = ["bah"] foo(list) print(list) Which Option is correct? A) ["hello","world"] is output because python passes the list by reference and the list is changed inside the function. B) ["bah"] is output because python passes the list by value so changes to the list in the function are made to a separate list than the one that is passed in. C) ["bah"] is output because python passes...
JavaScript Use the browser tools to identify the lines missing var keywords, add the keywords in...
JavaScript Use the browser tools to identify the lines missing var keywords, add the keywords in your text editor. <html>         <body>                 <header>                    <h1>                       Hands-on Project 4-3                    </h1>                 </header>                               <article>                    <div id="results">                        <p id="resultsExpl"></p>                        <ul>                           <li id="item1"></li>                           <li id="item2"></li>                           <li id="item3"></li>                           <li id="item4"></li>                           <li id="item5"></li>                        </ul>                    </div>                    <form>                        <fieldset>                          <label for="placeBox" id="placeLabel">                            Type the name of a place, then click Submit:                          </label>                          <input type="text" id="placeBox" />                        </fieldset>                        <fieldset>                          <button type="button" id="button">Submit</button>                        </fieldset>                    </form>                 </article>                 <script>                    var places = []; //...
JavaScript Given the following object, log every property name and value to the console using a...
JavaScript Given the following object, log every property name and value to the console using a loop. let myObj = { id: 12 name: 'My Object', class: 'obj', height: 65, likeJavascript: true, data: [1, 53, 23] };
Given: E[x] = 4, E[y] = 6, Var(x) = 2, Var(y) = 1, and cov(x,y) =...
Given: E[x] = 4, E[y] = 6, Var(x) = 2, Var(y) = 1, and cov(x,y) = 0.2 Find a lower bound on (5 < x + y < 10). State the theorem used.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT