Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
JavaScript Linked Stack

I am practicing data structures on JavaScript, and wrote a stack based linked list. However, three of my methods pop() peek() and toString() are faulty because they return undefined values, whereas I would like them to return the numerical values. The rest of the stack methods are working fine! Could this be a scoping issue? Thank you for your time and help.

Updated working code is below after the comment suggestions!

class Node {
    /* Creates a node with the given element and next node */
    constructor(e, n) {
        this.data = e;
        this.next = n;
    }
}

class LinkedStack {
    /* Creates an empty stack */
    constructor() {
        this.top = null;
        this.size = 0;
    }

    push = (elem) => {
        let v = new Node(elem, this.top);
        this.top = v;
        this.size++;
    }

    length = () => {
        return this.size;
    }

    isEmpty = () => {
        return this.size === 0;
    }

    peek = () => {
        if (this.isEmpty()) {
            console.log("Empty Stack");
        }
        return this.top.data;
    }

    pop = () => {
        if (this.isEmpty()) {
            console.log("Empty Stack");
        }
        const temp = this.top.data;
        this.top = this.top.next;
        this.size--;
        return temp;
    }

    toString = () => {
        let s = "[";
        let cur = null;
        if (this.length() > 0) {
            cur = this.top;
            s += cur.data;
        }

        if (this.length() > 1) {
            for (let i = 1; i <= this.length() - 1; i++) {
                cur = cur.next;
                s += ", " + cur.data;
            }
            s += "]";
            return s;
        }
    }
}

let stack = new LinkedStack();
stack.push(9);
console.log(stack.pop() + " was popped"); // undefined, but stack size decreases
stack.push(12);
stack.push(15);
console.log("Is Stack Empty? " + stack.isEmpty());
console.log("Stack Length: " + stack.length());
console.log("Top value: " + stack.peek());
console.log("Stack Content: " + stack.toString()); // Stack content [15, undefined]

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda