What is the best way to practice solving linked list problems from LeetCode on your personal computer?

Is there a way to execute the linked list programs on my local machine? I am able to run this code in their input field, but I'm having trouble running it on my local machine.

  function ListNode(val, next) {
      this.val = (val===undefined ? 0 : val)
      this.next = (next===undefined ? null : next)
  }
 
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */

var mergeTwoLists = function (l1, l2) {
  var mergedHead = { val: -1, next: null },
    crt = mergedHead;
  while (l1 && l2) {
    if (l1.val > l2.val) {
      crt.next = l2;
      l2 = l2.next;
    } else {
      crt.next = l1;
      l1 = l1.next;
    }
    crt = crt.next;
  }
  crt.next = l1 || l2;
  return mergedHead.next;
};

mergeTwoLists([1, 2, 4], [1, 3, 4]);

Answer №1

If you want to convert an array to a linked list and vice versa, you can make use of these handy helper functions. They essentially perform the same task as the LeetCode framework does in the background.

const convertArrayToList = arr => arr.length ? new ListNode(arr[0], convertArrayToList(arr.slice(1)))  
                                    : null;
const convertListToArray = head => head ? [head.val].concat(convertListToArray(head.next)) 
                                   : [];

Here's an example of how you can utilize these functions:

const convertedArray = convertListToArray(
    mergeTwoLists(convertArrayToList([1, 2, 4]), convertArrayToList([1, 3, 4]))
);

Answer №2

After creating custom ListNode and LinkedList classes, I successfully ran the mergeTwoLists method locally. The code snippet below showcases how the runCase function merges two ListNodes (heads of linked lists) and prints the result. To generate a linked list from LeetCode test case inputs, we can use the toArray method and convert the result back to an array using the fromArray function available in the LinkedList class.

class ListNode {
  constructor(val=0, next=null) {
      this.val = val;
      this.next = next;             
  }
}

class LinkedList {
  constructor(head = null) {
    this.head = head
  }

  static fromArray(array) {
    const linkedList = new LinkedList();

    for (let i = array.length - 1; i >= 0; i--) {
      const node = new ListNode(array[i]);
      node.next = linkedList.head;
      linkedList.head = node;
    }

    return linkedList;
  }

  toArray() {
    const array = [];
    let current = this.head;

    while (current) {
      array.push(current.val);
      current = current.next;
    }

    return array;
  }
}

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 *
 * @param {ListNode} node1
 * @param {ListNode} node2
 * @return {ListNode}
 */
var mergeTwoLists = function(node1, node2) {
  let loco = new ListNode();
  let current = loco;

  while (node1 && node2) {
    if (node1.val > node2.val) {
      current.next = node2;
      node2 = node2.next;
    } else {
      current.next = node1;
      node1 = node1.next;
    }
    current = current.next;
  }
  current.next = node1 || node2;

  return loco.next;
};

const runCase = (array1, array2) => {
  const node1 = LinkedList.fromArray(array1).head;
  const node2 = LinkedList.fromArray(array2).head;

  const result = mergeTwoLists(node1, node2);
  const linkedList = new LinkedList(result);
  console.log(linkedList.toArray());
}

runCase([1, 2, 4], [1, 3, 4]); // [1,1,2,3,4,4]
runCase([], []); // []
runCase([], [0]); // [0]

Reference

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a clickable button within an image container using Bootstrap 5

I am attempting to create a button inside an img element, specifically in the center of that img element within Bootstrap 5. The image is not being used as a background on the grid and I am applying some hover animations to zoom in. I am curious if there ...

The use of asterisk (*) in importing dynamically

Hello everyone, I'm currently working on a project structure that looks like this: intranet ├── modules │ ├── storage │ │ ├── views │ │ └── route │ │ └── index.js │ │ │ ├── ...

What is the most efficient way to transform an array of objects into a compact string?

I'm exploring a new project with an import/export feature in mind. Initially, I will have an array containing approximately 45 simple objects structured like this: {"id": "someId", "quantity": 3} To make it exportable, t ...

In the conditional statement, document location or window location href will be ineffective in the if clause but will be functional in the else clause

When validating a password in a form, I have encountered an issue where the code only works for one specific outcome. If the correct password is entered, the user should be moved to site X, but if it's incorrect after 3 tries, they should be moved to ...

Retrieve data from two separate files and store it as a two-dimensional array in JavaScript

Is there a way to read and convert two .txt files into a 2d array? I currently have a code snippet that looks like this : var fs = require('fs') file = './text1.txt' fs.readFile(file,'utf-8', (e,d) => { textByLine = d.s ...

"Can you help me figure out how to transform a date string into a concise date object using JavaScript

As a newcomer to UI coding, I am faced with the challenge of working with date data from JSON in the format "2021-02-28 00:00:00". However, when writing to an xlsx file, I need the date to be in a different format rather than as a string. Here is my attemp ...

Step-by-step guide to implementing a sticky header while scrolling

How can I implement a fixed header on scroll, like the one seen on this website: www.avauntmagazine.com Here is the HTML for my header: <div class="bloc bgc-wild-blue-yonder l-bloc " id="bloc-1"> <div class="container bloc-sm"> &l ...

Upon migrating from Vue CLI 2 to 3, an error is thrown stating: "Cannot locate element: #app" and an empty body is

Currently, I am in the process of transitioning my VueJS project from VueCLI 2 to version 3. After moving all the necessary files to the src folder, I attempted to view it in the browser by running npm run serve. However, I encountered a problem where the ...

Printing HTML to a VueJS page is simple and efficient

I have a situation where one of my attributes in a property contains an HTML string. Instead of rendering the HTML as expected, when I output it within my template, the browser displays the raw HTML code with tags intact. It doesn't interpret it as a ...

Ways to prevent the jQuery simple slider from transitioning slides while it is in an invisible state

There is a jQuery slider on my website that behaves strangely when I navigate away from the Chrome browser and return later. It seems to speed through all pending slides quickly when it was not visible. Now, I want the slider to pause when it becomes invi ...

Facing a node.js installation issue on Windows 10 while using Visual Studio Code (VS

Issue encountered while trying to execute "DownloadString" with one argument: Unable to establish a secure connection due to SSL/TLS channel creation failure. At line:1 char:1 + iex ((New-Object System.Net.WebClient).DownloadString('https ...

Unusual patterns observed when employing the splice method in AngularJS for ordering

Take a look at this Plunker demo link I have encountered an issue after implementing the orderby feature (line 24) in my application. When I try to add an item without priority and then add another one with priority, followed by deleting the first item, t ...

Stop Code Execution || Lock Screen

Is there a way to address the "challenge" I'm facing? I'm an avid gamer who enjoys customizing my game using JavaScript/jQuery with Greasemonkey/Firefox. There are numerous scripts that alter the DOM and input values. In my custom script, I hav ...

Determine if a SQL column exists following a SELECT statement

I have a query that I need help with: let selectQuery = "select * from mainTable where username = '"+ username + "'"; In my code, I am trying to make sure that childtable2id exists in the table. Here is what I have so far: for (let i = 0; i & ...

What is the best way to retrieve information from a JavaScript file?

Learning.vue <template> <div> <button @click="test()">test</button> </div> </template> <script> import records from './records.js' export default { data () { return { ...

A guide on implementing reverse routes using react-router

Is there a best practice for constructing URLs for links in my react-router based app? In the Zend Framework world of php, I would use a url helper that utilizes reverse routes. By providing the route name and parameters to a route configuration, it would ...

Access the Vue instance from a different element instance

I've developed a leaflet map using vue.js. There's a method I've created called 'showSubmit' that needs to be triggered on the leaflet marker moveend event. Here's what I'm currently doing: this.map.markers.user.on("move ...

How can the token be verified when authorizing Google OAuth 2.0 on the server side?

Unable to validate the user token ID on the server side despite following Google's guide at https://developers.google.com/identity/sign-in/web/backend-auth In JavaScript, I retrieve the id token and send it to the server: var googleUser = auth2.cur ...

When state updates in React, the component will rerender without affecting its style

There seems to be a minor oversight on my part. The issue arises in the parent component where I maintain a state of selected items, which are added from the child component. The background color of the child component changes when an item is selected. Ad ...

Using AJAX to inject JSON data from PHP into Edge Animate

For a school assignment, I am currently working on a project using edge animate. My objective is to import data from a database hosted on my school's webspace and incorporate it into the edge animate project. Despite researching online for a solution ...