Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Cómo agregar un elemento a una lista enlazada serializada en Javascript

Si serializo una lista vinculada a JSON y la almaceno en un archivo de texto

 const list = new SinglyLinkedList(); list.push('Hello'); list.push('World'); list.push('!'); list.print(); fs.writeFile('./test.txt', JSON.stringify(list), err => { if (err) { console.log(err); return; } })

Puedo leer el archivo y deserializar los datos para recuperar la lista vinculada, pero ¿qué pasa si quiero agregar un nuevo elemento en la lista vinculada? La serialización solo guarda el estado obj.

¿Hay alguna forma de agregar un nuevo elemento a esta lista y volver a serializarlo?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

JSON.parse solo puede producir algunos tipos de datos: booleano, número, cadena, null , matriz y objeto simple. No puede producir una instancia de una clase personalizada.

Para facilitar ese proceso, aquí hay algunas ideas:

  • No es necesario serializar las next referencias de una lista enlazada, ya que su orden define de forma única estos enlaces implícitamente.
  • Serialice una lista enlazada como si fuera una matriz.
  • Haga que sus instancias de listas enlazadas sean iterables. De esta manera, es fácil convertir una instancia en una matriz (y serializarla).
  • Implemente el método toJSON , que es llamado por JSON.stringify
  • Permita que el constructor de la lista enlazada tome cualquier cantidad de argumentos, que se agregan a la nueva lista de inmediato. Esto es muy parecido a lo que permite el constructor Array .
  • Implemente un método fromJSON estático que tome una cadena JSON y devuelva una instancia de lista vinculada para ella.

Aquí está eso implementado:

 class SinglyLinkedList { static Node = class { constructor(value, next=null) { this.value = value; this.next = next; } } constructor(...values) { this.head = this.tail = null; for (let value of values) this.push(value); } push(value) { let node = new SinglyLinkedList.Node(value); if (this.tail) { this.tail = this.tail.next = node; } else { this.head = this.tail = node; } } * [Symbol.iterator]() { for (let node = this.head; node; node = node.next) { yield node.value; } } toJSON() { return [...this]; } static fromJSON(json) { return new this(...JSON.parse(json)); } } // Demo // 1. Constructor can accept values to be added to the list const list = new SinglyLinkedList('Hello', 'World', '!'); // 2. A linked list can be iterated, so no specific print method is needed console.log(...list); // 3. JSON.stringify will call toJSON method let serialized = JSON.stringify(list); console.log(serialized); // 4. fromJSON can be used to create a linked list instance from Array-like JSON let restored = SinglyLinkedList.fromJSON(serialized); // Again, iteration can be used for printing console.log(...restored);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!