Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda