What is the functionality of the node class within a doubly linked list?

Within the Node class, the next property can only be assigned a value of type Node or null.

class Node {
  value: any;
  next: Node | null;
  prev: Node | null;

  constructor(value: any) {
    this.value = value;
    this.next = null;
    this.prev = null;
  }
}

However, it seems that in the push function, specifically in the line "this.tail!.next = newNode;", we are assigning just the reference of the newNode to the next property. This means that newNode is merely a reference and does not contain values for next or prev like in the Node class.

push(value: any) {
    const newNode = new Node(value);
    if (this.length === 0) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail!.next = newNode;
      newNode.prev = this.tail;
      this.tail = newNode;
    }
    this.length++;
    return this;
  }

This raises the question of how a reference alone can suffice as the value of next, instead of an instance of Node with defined properties.

Answer №1

When working with TypeScript, objects are always treated as references. Unlike in C where you have a specific type of variable called 'struct' for a 'Node', in TypeScript and JavaScript, the 'object' itself is considered to be a reference. The dot operator in TypeScipt and JavaScript acts like the '->' in C when accessing properties. In this scenario, the 'newNode' refers to an object that has been initialized with properties such as 'value', 'next', and 'prev'.

If we take the example of having a list with one node containing the value '1', it can be visualized like this:

 list
  ↓
┌───────────┐   
│ head: ───────►
│ tail: ───────►
│ length: 1 │   
└───────────┘  

Now, if 'list.push(2)' is triggered, the constructor method 'new Node(2)' is executed which initializes the object's properties and returns the reference to be stored in 'newNode':

 list
  ↓
┌───────────┐   
│ head: ───────►
│ tail: ───────►
│ length: 1 │   
└───────────┘  

                ┌────────────┐
                │ prev: null │
                │ value: 2   │
                │ next: null │
                └────────────┘
                   ↑
                 newNode

Subsequently, 'this.tail!.next = newNode;' copies that reference:

 list
  ↓
┌───────────┐    
│ head: ───────►
│ tail: ───────►
│ length: 1 │   
└───────────┘   

                ┌────────────┐
                │ prev: null │
                │ value: 2   │
                │ next: null │
                └────────────┘
                   ↑
                 newNode

The statement 'newNode.prev = this.tail;' sets up the link in the opposite direction:

 list
  ↓
┌───────────┐    
│ head: ───────►
│ tail: ───────►
│ length: 1 │   
└───────────┘   

                ┌────────────┐
                │ prev: null │
                │ value: 2   │
                │ next: null │
                └────────────┘
                   ↑
                 newNode

Finally, 'this.tail = newNode;' and 'this.length++' complete the operation:

 list
  ↓
┌───────────┐    
│ head: ───────►
│ tail: ────────┐ 
│ length: 1 │  
└───────────┘    
             

                ┌────────────┐
                │ prev: null │
                │ value: 2   │
                │ next: null │
                └────────────┘
                   ↑
                 newNode

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

What is the best way to display user data exclusively in Angular?

How can I ensure that users only have access to their own information rather than the entire database? I attempted to use an if-else statement to filter out the data I need, as shown in the example below, but it was unsuccessful. custom-history.component ...

I'm having trouble getting my Node.js and TypeScript project to run because I keep encountering the error message ".ts is recognized as an unknown file extension."

I encountered the following error message: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" This issue arose after inserting "type": "module" into the package.json package.json { "name": &qu ...

An error is encountered when attempting to retrieve the list using axios

For this project, I am required to fetch a list from the following resource: http://jsonplaceholder.typicode.com/photos The controller setup is as follows: @JsonController('/photo') @Service() export class PhotoController { const ...

Angular JS and TypeScript - Issue: ng:areq Invalid Argument "Argument 'XXXXXX' is not a function, received undefined"

Encountering a specific error mentioned in the title. I organized models and controllers into distinct files saved under models and controllers folders respectively. Upon trying to establish a connection between them, I received an error stating "ng:areq ...

I encountered an issue with Angular where it is throwing an error stating that the property 'catch' does not exist on the type 'Observable<Object>'

I have been working on an angular application that interacts with a python flask API. During development, I encountered the need to display results passed from the backend. To achieve this, I created an angular service. Below is the code for the angular s ...

What is the reason behind the warning about DOM element appearing when custom props are passed to a styled element in MUI?

Working on a project using mui v5 in React with Typescript. I am currently trying to style a div element but keep encountering this error message in the console: "Warning: React does not recognize the openFilterDrawer prop on a DOM element. If you in ...

No types are assigned to any props

I recently began working on a SvelteKit skeleton project for my personal website. However, I encountered an error when using Svelte with TypeScript - specifically, I kept getting the message Type '<some prop type>' is not assignable to type ...

When configuring Gatsby with Typescript, you may encounter the error message: "You cannot utilize JSX unless the '--jsx' flag is provided."

I am currently working on a Gatsby project and decided to implement Typescript into it. However, I encountered an error in my TSX files which reads: Cannot use JSX unless the '--jsx' flag is provided. What have I tried? I consulted the docume ...

Encountering challenges with the search and filtering features

I'm having some trouble with the search and filter features I'm creating. They work fine initially, but once I enter a search query in the input field, the results show up as expected. However, if I delete the query or enter a different one, the ...

Updating a subscribed observable does not occur when pushing or nexting a value from an observable subject

Help needed! I've created a simple example that should be working, but unfortunately it's not :( My onClick() function doesn't seem to trigger the console.log as expected. Can someone help me figure out what I'm doing wrong? @Component ...

Double-executing methods in a component

I have encountered an issue while trying to filter existing Worklog objects and summarize the time spent on each one in my PeriodViewTable component. The problem I am facing involves duplicate method calls. To address this, I attempted to reset the value ...

Associate the generic operator <T> with a FunctionConstructor

In my TS function, I deserialize JSON into a specific type/object by providing it with a constructor function of that type which reconstructs the object from JSON. Here is how it looks like: export function deserializeJSON<T>(JSONString: string, ty ...

What is the best way to pass only the second parameter to a function in TypeScript?

Let's consider a TypeScript function as shown below: openMultipleAddFormModal(commission?: Commission, people?: People): void { // some data } To make a parameter optional, I have added the Optional Chaining operator. Now, how can I modify the code ...

What is the best way to create props that can accommodate three distinct types of functions in TypeScript?

I have been encountering a problem with the last function in my props interface that is supposed to support 3 different types of functions throughout the application. Despite adding parentheses as requested, I am still facing errors. // In Parent compon ...

Monitoring Object Changes in Angular 4

ETA: I am aware of different methods for monitoring my form for alterations. However, that is not the focus of my inquiry. As indicated by the title, my question pertains to observing changes within an object. The application displayed below is solely for ...

Access the plugin object from a Vue.js 2 component using typescript

I devised a plugin object to handle the regular expressions used in my application in a more global manner. Here's an example of how it looks: import Vue from "vue"; Vue.prototype.$regex = { //isEmail function implementation goes here } ...

Validator returns undefined when expressing invalid data

Having an issue with validation, here is the code snippet: routes.js var express = require('express'); var router = express.Router(); var hello_controller = require('../api/controllers/helloController'); var { validationRules, validat ...

Tips on exporting a basic TypeScript class in an Angular 4 module

I am facing a challenge with packaging a TypeScript class as part of an Angular module for exporting it as a library using ng-packagr. For instance, here is my class definition - export class Params { language: string ; country: string ; var ...

Convert data into a tree view in JavaScript, with two levels of nesting and the lowest level represented as an array

Here is an example of a JSON object: [ { "venueId": "10001", "items": [ { "venueId": "10001", "locationId": "14", "itemCode": "1604", "itemDescription": "Chef Instruction", "categoryCode": "28", ...

how to use all parameters except the first one in TypeScript

Is there a way to reference one function's parameter types in another function, but only use a subset of them without repeating the entire list of parameters? //params of bar should be same as foo, except p1 should be a different type function foo(p1 ...