Aún no tienes acceso a esta clase

Crea una cuenta y continúa viendo este curso

Construyendo un Stack

17/25
Recursos

Aportes 119

Preguntas 7

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

IMPORTANTE

Quiero que notes como el método peek lo único que hace es tomar el último elemento, sin embargo, NO lo elimina, ¿Qué pasaría si escribieras peek dos veces?

myStack.peek()
myStack.peek()

Pues las dos veces te va a devolver el mismo valor porque el elemento top nunca fue eliminado. Por tanto, no tendrías forma de acceder a los otros elementos que están en el stack, es por eso que el método peek suele ir acompañado del método pop:

myStack.peek()
myStack.pop()

De esta forma tomas el primer elemento al top de la pila y a su vez lo eliminas del top ^^

Lo pude resolver con el pop ya esta y te lo comparto 😄, hoy es 24 de diciembre asi que te deseo feliz noche buena y feliz navidad

  pop() {
    if (!this.length) {
      console.error("There is no nodes in the stack.");
      return;
    }
    const topNode = this.top;
    if (this.length === 1) {
      this.top = null;
      this.bottom = null;
    } else {
      this.top = this.top.next;
    }
    this.length--;
    return topNode
  }
}```

Fue un placer haber estado en este curso, estoy en plazti Day me quedan 20min asi que fue un placer, hasta aqui llego.

😀 Construyendo un Stack en Dart.

class Node{
  var value;
  var next;
  Node(this.value);
}

class Stack{
  var top;
  var bottom;
  int length = 0;

  dynamic peek() => top;

  dynamic push(var value){
    final newNode = Node(value);
    if(length == 0){
      top = newNode;
      bottom = newNode;
    }else{
      final holdingPointer = top;
      top = newNode;
      top.next = holdingPointer;
    }

    length++;
    return this;
  }

  dynamic pop(){
    final node = top;
    if(length == 0){
      return 'Error: Stack empty.';
    }else if(length == 1){
      top = node.next;
      bottom = null;
      length--;
    }else{
      top = node.next;
      length--;
    }

    return this;
  }
}
import 'stack.dart';

void main(List<String> arguments){
  final stack = Stack();
  stack.push(1);
  stack.push(2);
  stack.push(3);
  stack.peek();
  print(stack.length);
  stack.pop();
  print(stack.length);
}

Mi código sin ver la clase. Espero no tener muchas correcciones.

class Node {
    constructor(value){
        this.value = value
        this.prev = null
    }
}

class Stack{
    constructor(){
        this.top = null
        this.bot = null
        this.lenght = 0
    }

    push(value){
        let newNode = new Node(value)
        if (this.lenght == 0){
            this.bot = newNode
        }
        newNode.prev = this.top
        this.top = newNode
        this.lenght++
        return this
    }
}

let stack = new Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

class Stack {
    constructor() {
        this.top = null;
        this.bottom = null;
        this.length = 0;
    }

    peek() {
        return this.top;
    }

    push(value) {
        const newNode = new Node(value);
        if (this.length === 0) {
            this.top = newNode;
            this.bottom = newNode;
        } else {
            newNode.next = this.top;
            this.top = newNode;
        }
        this.length++;
        return this;
    }

    pop() {
        if (this.length === 0) {
            return undefined;
        }
        const removedNode = this.top;
        if (this.length === 1) {
            this.top = null;
            this.bottom = null;
        } else {
            this.top = removedNode.next;
        }
        this.length--;
        return removedNode;
    }
}
pop() {
  if (this.length === 0) {
    return
  } else if (this.length === 1) {
    this.top = null;
    this.bottom = null;
  } else {
    this.top = this.top.next;
  }

  this.length --;
  return this;
}	

Mi código para el método pop( )

pop(){
        if (this.length == 0) {
            console.log("Objeto vacio");
            return this;
        }
        const holdingNode = this.top.next;
        this.top = holdingNode;
        this.length --;
        return this;
    }

Al fin uno que resuelvo en poco tiempo jaja.

class Node{
    constructor(value){
        this.value = value;
        this.next = null;
    }
}

class Stack{
    constructor(){
        this.top = null;
        this.bottom = null;
        this.length = 0;
    }

    peek(){
        return this.top;
        
    }

    push(value){
        const point = new Node(value);

        if (this.length === 0){
            this.top = point;
            this.bottom = point;
        }else{
            const lastTop = this.top;
            this.top = point;
            this.top.next = lastTop;
        }

        this.length ++;

        return this;
    }

    pop(){
        const newTop = new Node(this.top.next);
        const newNext = this.top.next;

        this.top =newTop;
        this.top.next = newNext;


       this.length --;
       return this;
    }
}

let myStack = new Stack();

myStack.push(2);
myStack.push(6);
myStack.push(8);
myStack.push(4);


myStack.pop();


<code> 
    public pop(){
        if(this.length === 0){
            console.error("cannot pop last element if Stack is empty")
        }else{
            if (this.top){
                if(this.top.previous){
                    let newTopNode : StackNode = this.top.previous
                    this.top = newTopNode
                    if(!this.top.previous){
                        this.bottom = this.top
                    }
                    this.length = this.length - 1
                }
            }else{
                console.error("there is no top or top.previous to make the new top")
            }
        }
    }

Aquí les comparto mi solución del método pop()

	pop() {
		if (this.length === 0) {
			return "pila vacía.";
		} else {
			this.top = this.top.next;
		}
		this.length--;
		return this;
	}

my pop :😃

pop()
    {
        if(this.lenght > 0)
        {

            this.top = this.top.next;
            if(this.lenght === 1)
            {
                this.bottom = null; 
            }
            this.lenght--;
            
            return this;
        }
        else
        {
            return new Error('stack is empty');
        }
        
    }

My version of pop() stack function:

  pop(){
    if (this.length === 0) {
      throw new Error("stack is already empty");
    }
    if (this.length === 1) {
      this.top = null;
      this.bottom = null;
      this.length--;
      return this;
    }
    this.top = this.top.next;
    this.length--;
    return this;
  }

Aqui dejo mi solución al metodo pop

pop()
  {
    if(this.length <= 0) return 'No hay elementos en el stack' // Primero verifico si hay elementos en el stack 
    const view = this.top
    this.top = this.top.next
    this.length--
    return view
  }
pop(){
    if(this.length){
        if(this.top.next){
            this.top = this.top.next;
        }else{
            this.top = null;
            this.bottom = null;
        }
        this.length--;
    }
    return this;
}
  pop() {
    if (this.length === 1) {
      this.top = null;
      this.bottom = null;
    } else {
      this.top = this.top.next;
    }

    this.length--;

    return this;
  }

Aquí mi código con el método de pop:

class Node{
	constructor(value){
		this.value = value;
		this.next = null;
	}
}
class Stack {
	constructor(){
		this.top = null;
		this.bottom = null;
		this.length = 0;
	}

	peek(){
		return this.top; //Se hace referencia sobre el stack

	}

	push(value){
		const newNode= new Node(value);
		if(this.length === 0)	{
			this.top = newNode;
			this.bottom = newNode

		}	else	{
			const holdingPointer = this.top;
			this.top = newNode;
			this.top.next = holdingPointer;
		}
			this.length++

			return this;
	}

	pop(){
		const holdingPointer = this.top.next;
		delete this.top;
		this.top = holdingPointer;
		this.length--
	}
}

Mi código un poco más simplificado:

class Node {
  constructor(value) {
    this.value = value
    this.next = null
  }
}

class Stack {
  constructor() {
    this.top = null
    this.bottom = null
    this.length = 0
  }
  peek() {
    return this.top
  }
  push(value) {
    const newNode = new Node(value)
    if (!this.top) { //Si no hay un "top" entonces el nuevo nodo es el primer "top" y el "bottom" al mismo tiempo
      this.bottom = newNode
    }
    newNode.next = this.top // En el caso que del primer nodo el "next" sería igual al "top" de ese momento, es decir a "null".  Para los siguientes nodos, el "next" apunta al nodo "top" de ese momento, y luego se asigna el "top" al nuevo nodo.
    this.top = newNode
    this.length++
    return this
  }
  pop() {
    if (!this.top) { // Si no hay un "top", entonces no puede remover ningún nodo
      return null
    }
    this.top = this.top.next // Con redefinir el "top" al "next" de el mismo, se elimina el nodo automáticamente.
    if (this.top === null) { // Si el "top" llega a ser "null", entonces el "bottom" también debe ser null
      this.bottom = null
    }
    this.length--
    return this // Retorno todo el stack para pruebas.  Si se quiere devolver el nodo eliminado hay que guardarlo en una variable antes de reasignar el "top".
  }
}

const myStack = new Stack()
myStack.push(1)
myStack.push(2)
myStack.push(3)
myStack.peek()
myStack.pop()
myStack.pop()
myStack.pop()

Mí método pop():

pop(){
        if(this.length === 0){
            console.log('no items to delete')
            return
        }
        const holdingPointer = this.top.next
        this.top = holdingPointer
        this.length--
        return this
    }

En el código ya está agregado el reto del curso, el método pop 😄

  class Node {
    constructor(value) {
      this.value = value;
      this.next = null;
    }
  }

  class stack {
    constructor() {
      this.top = null;
      this.bottom = null;
      this.length = 0;
    }
    peek() {
      return this.top
    }
    pop() {
      const getout = this.top;
      this.top = this.top.next;
      getout.next = null
      this.length--
      return getout;
    }
    push(value) {
      const element = new Node(value);
      if (this.length == 0) {
        this.top = element;
        this.bottom = element;
      } else {
        element.next = this.top;
        this.top = element
      }
      this.length++
      return this;
    }
  }

  const myStack = new stack();
  myStack.push(2);
  myStack.push(32);
  myStack.push(43);
  myStack.push(3);
  myStack.push(4);
  myStack.push(1);
  myStack.push(54);
  myStack.push(12);
  myStack.push(44);
  myStack.push(7);
  myStack.push(6);

  //COMANDOS PARA PROBAR

  myStack.peek();
  myStack.pop();

Codigo bomnito

//Simple stack implementation
//@method push: pushes an element to the stack
//@method pop: pops an element from the stack
//@method peek: returns the top element of the stack
//@method print: prints the stack
const Node = require("../node");

class Stack {
    constructor() {
        this.top = null;
        this.bottom = null;
        this.length = 0;
    }

    peek() {
        return this.top;
    }
    push(value) {
        const newNode = new Node(value);

        if (this.length === 0) {
            this.top = newNode;
            this.bottom = newNode;
        } else {
            const lastTop = this.top;
            this.top = newNode;
            this.top.next = lastTop;
        }
        this.length++;
        return this;
    }

    pop() {
        if (this.length === 0) return undefined;
        const lastTop = this.top;
        this.top = this.top.next;
        this.length--;
        if (this.length === 0) {
            this.bottom = null;
        }
        return lastTop;

    }




    print() {
        let current = this.top;
        while (current) {
            console.log(current.value);
            current = current.next;
        }
    }
}


module.exports = Stack;

Método Pop!

    pop() {
        const holdingPointer = this.peek();;

        if (this.length > 1) {
            this.top = this.top.next;

            holdingPointer.next = null;
        } else {
            this.top = null;
            this.bottom = null;
        }

        if (this.length > 0) {
            this.length--;
        }

        return holdingPointer;
    }

Mi método pop.

pop(){
    const nodeToDelete = this.top;
    const nodeToDeleteValue = nodeToDelete.value;
    if(this.length == 1){
        this.top = null;
        this.bottom = null;
    }else{
        this.top = this.top.next; 
        nodeToDelete.next = null;
    }
    
    this.length--;
    return nodeToDeleteValue;
}

Les comparto como quedó el método pop utilizando una pequeña validación sobre cuantos elementos existen en el stack

 pop(){
        if(this.length === 0) {
            return this
        } else if(this.length === 1) {
            delete this.last
            delete this.first
            this.length-=1
        } else {
            const newLast = this.last.next  
            delete this.last
            this.last = newLast 
            this.length-=1
        }

        return this

Esta es mi solución a la función pop()

pop() {
	if (this.length === 1) {
		this.top = null;
		this.bottom = null;
	} else if(this.length > 1) {
		const removeTheLastPointer = this.top.next;
		this.top = removeTheLastPointer;
	} else {
		return this;
	}

	this.length--;
	return this;
}

Que tal campeon, buen dia.
comparto mi codigo.

class Node {
  constructor(value){
    this.value = value;
    this.next = null;
  }
}

class Stack {
  constructor(){
    this.top = null;
    this.bottom = null;
    this.length = 0;
  }
  push(value){
    const newNode = new Node(value);
    if (value === undefined) {
      return null
    }
    if(!this.length){
      this.top = newNode;
      this.bottom = newNode;
    } else {
      newNode.next = this.top;
      this.top = newNode;
    }
    this.length++;

    return this;
  }
  pop() {
    let message = {Error: 'The Stack is Empty'};
    const stackList  = this.top;
    
    if (this.length === 0) {
      throw new Error(message.Error);
    }
    if (this.length === 1) {
      this.top = null;
      this.bottom = null;
    } else {
      this.top = this.top.next;
    }
    this.length--;

    return stackList;
  }
  peek() {
    return this.top;
  }
  getStackList() {
    let currentList = this.top;
    let stack = '';

    for (let i = 0; i < this.length; i++) {
      stack += `${currentList.value}${i === this.length - 1 ? '' : ' '}`;
      currentList = currentList.next    
    }

    return stack;
  }
}

const myStackList = new Stack();

Así me quedo el método pop

pop(){
    if(this.length === 0){
        console.error("Este stack no tiene elementos")
        return this
    }else if(this.length === 1){
        this.bottom = null
        this.top = null
    }else{
        this.top = this.top.next
    }
    this.length--
    return this
}

He aquí mi solucion para el método de pop()

class Node {
	constructor(value) {
		this.value = value;
		this.next = null;
	}
}

class Stack {
	constructor() {
		this.top = null;
		this.bottom = null;
		this.length = 0;
	}
	peek() {
		return this.top;
	}
	push(value) {
		const newNode = new Node(value);
		if (this.length === 0) {
			this.top = newNode;
			this.bottom = newNode;
		} else {
			const holdingPointer = this.top;
			this.top = newNode;
			this.top.next = holdingPointer;
		}

		this.length++;
		return this;
	}
	pop() {
		if (this.length === 0) {
			console.error("this stack it's already empty");
			return this;
		} else if (this.length === 1) {
			this.top = null;
			this.bottom = null;
			this.length--;
			return this;
		} else {
			const newTop = this.top.next
			this.top = newTop;
			this.length--;
			return this;
		}
	}
}

const myStack = new Stack();

Les comparto mi código de toda la implementación de la pila. Cualquier corrección o mejora es bienvenida.

class Node{
  constructor(value){
    this.value = value;
    this.next = null;
  }
}

class Stack{
  constructor(){
    this.top = null;
    this.bottom = null;
    this.length = 0;
  }
  peek(){
    return this.top;
  }
  push(value){
    const newNode = new Node(value);
    if (this.length == 0) {
      this.top = newNode;
      this.bottom = newNode;
    } else {
      newNode.next = this.top;
      this.top = newNode;
    }
    this.length++;
    return this;
  }
  pop(){
    if (this.length === 0) 
      throw new Error ("The Stack is empty"); 

    const topNode = this.top;
    if (this.length === 1){
      this.top = null;
      this.bottom = null;
    }else {
      this.top = this.top.next
    }
    this.length--;
    return topNode;
  }
}

Estas son las pruebas que le hice.

let myStack = new Stack();
console.log(myStack.push(1));
console.log(myStack.push(2));
console.log(myStack.push(3));
console.log(myStack.push(4));
console.log(myStack.peek());
console.log(myStack.peek());
console.log(myStack.pop());

Aquí mi ejercicio completo, me ahorré un paso en e método push y en el método pop utilice un switch para hacer las validaciones.

class Node{
    constructor(value){
        this.value = value;
        this.next = null;
    }
}
class Stack{
    constructor(){
        this.top = null;
        this.bottom = null;
        this.length = 0;
    }
    peek(){        
        return this.top;        
    }
    push(value){
        const newNode = new Node(value);
        if(this.length === 0){
            this.bottom = newNode;
            this.top = newNode;
        }else{            
            this.top.next = newNode;
            this.top = newNode;
        }   
        this.length++;     
        return this;
    }
    pop(){
        let pointer = this.bottom;
    switch (this.length) {
        case 0:
            return this;
        case 1:
            this.bottom = null;
            this.top = null;
            this.length--;
            return this;
        default:
            while(pointer.next.next){
                pointer = pointer.next;
            }
            pointer.next = null;
            this.top = pointer;
            this.length--;
            return this;
    }        
    }
}
const myStack = new Stack();
myStack.push(1)
myStack.push(2)

Este es mi aporte del metodo pop()

  pop() {
    this.top = this.top.next;
    if (this.length === 1) {
      this.bottom = null;
    }
    this.length--;
    return this;
  }

Mi solución para el método pop():

    pop() {

        if (this.lenght >= 0) {
            const nodePreviousTop = this.top.next;
            this.top = nodePreviousTop;
        } else {
            return 'Index out of bounds range.';
        }
        
        this.lenght--;

        return this;
    }

Les comparto mi implementación del Stack:

class Node {
  constructor(value) {
    this.value = value
    // In this case the next node is the one which is bellow
    this.next = null
  }
}

class Stack {
  constructor() {
    this.top = null
    this.bottom = null
    this.length = 0
  }

  peek() {
    return this.top
  }

  push(value) {
    const node = new Node(value)
    this.length++

    if (this.length === 0) {
      this.top = node
      this.bottom = node

      return
    }

    const currentTop = this.top
    this.top = node
    this.top.next = currentTop
  }

  pop() {
    if (this.length === 0) throw new Error('Nothing to pop')

    this.top = this.top.next
    this.length--
  }

  toString() {
    let current = this.top
    let stack = ''

    for (let i = 0; i < this.length; i++) {
      stack += `${current.value}${i === this.length - 1 ? '' : '\n'}`
      current = current.next
    }

    return stack
  }
}

es demasiado satisfactorio cuando pienso una lógica (En este caso el metodo pop(),) y me funciona. que genial! gracias Diego.

este es un stack de nodos pero puede ser con array u otro tipo de estructura

class Node {
  constructor(value){
    this.value = value
    this.next = null
  }
}
class Stack {
  constructor(){
    this.stack = null
    this.length = 0
  }
  peek(){
    return this.top
  }
  push(value){
    const node = new Node(value)
    if (this.length == 0) this.stack = node
    else {
      node.next = this.stack
      this.stack = node
    }
    this.length++
  }
  pop(){
    if (!this.length) return 'El stack esta vacio'
    this.stack = this.stack.next
    this.length--
  }
}

let stack = new Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
stack.pop()
stack.pop()
stack.pop()
stack.pop()
stack.pop()
// stack.pop()



stack

Mi método pop:

pop() {
    if (this.length !== 0) {
        this.top = this.top.next;
        this.length -= 1;
        if (this.length === 0) {
            this.bottom = null;
        }
    }
    return this;
}

😊

pop() {
        let pointer = this.top.next;

        delete this.top;

        this.top = pointer;

        this.length--;
        return this;
    }
class Node {
    constructor(value) {
        this.value = value 
        this.next = null
    }
}

class Stack {
    constructor(){
        this.top = null
        this.bottom = null
        this.length = 0
    }

    peek(){
        return this.top
    }

    push(value){
        let newNode = new Node(value)
        if(this.length === 0){
            this.bottom = newNode
        }
        else{
            this.top.next = newNode
        }
        this.top = newNode
        this.length++
        return this
    }

    pop(){
        if(this.top === null){
            return this
        }
        const nodeToPop = this.top
        let currentNode = this.bottom
        while(currentNode.next !== this.top){
            currentNode = currentNode.next
        }
        currentNode.next = null
        this.top = currentNode
        this.length--
        return nodeToPop
    }
}

const myStack = new Stack()
myStack.push(1)
myStack.push(2)
myStack.push(3)
myStack.pop()
myStack.peek()

Mi método pop

  pop() {
    let item = {};
    if (this.length === 0) {
      return null;
    }
    if (this.length === 1) {
      item = this.top;
      this.top = null;
      this.bottom = null;
      this.length = 0;
    } else {
      item = this.top;
      this.top = item.next;
      this.length--;
    }

    return item;
  }

Hice las clases basandome en la logica que se utilizo con la linkedList … En teoria funciona

class Node{
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

class Stack {
    constructor() {
        this.stack = null;
        this.length = 0;
    }

    pop(){
        const last = this.stack.next;
        this.stack = last;
        this.length--;
        return this;
    }

    push(value){
        const node = new Node(value);
        node.next = this.stack;
        this.stack = node;
        this.length++;
        return this;
    }

    peek(){
        return this.stack.value;
    }
}

module.exports = Stack;

Mi pop()

    pop(){
        if (this.length > 0){
            this.top = this.top.next;
            this.length--;
            return this;
        }
    }

Mi solución al reto:

pop() {
	if (this.length === 0) {
		console.log('No hay elementos')
	} else if (this.length === 1) {
		this.top = null
		this.bottom = null
		this.length -= 1
	} else {
		const newTop = this.top.next
		this.top = newTop
		this.length -= 1
	}
	return this
}

Les comparto mi solución al reto, le agregue algunas condiciones para que no cause error cuando se ejecutan algunos métodos al estar vacio el stack.

class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

class Stack {
    constructor() {
        this.top = null;
        this.bottom = null;
        this.length = 0;
    }
    peek() {
        return (this.top != null) ? this.top.value : this.top;
    }
    push(value) {
        const newNode = new Node(value)
        if (this.length === 0) {
            this.top = newNode;
            this.bottom = this.top;
        } else {
            newNode.next = this.top
            this.top = newNode;
        }
        this.length++;
        return this;
    }
    pop() {
        if (this.length === 0) {
            return undefined;
        }
        if (this.length === 1) {
            this.bottom = null
        }
        const removedTop = this.top;
        const newTop = this.top.next;

        removedTop.next = null;
        this.top = newTop;

        this.length--;
        return removedTop.value;
    }
    print() {
        if (this.length === 0) {
            console.log("This stack is empty");
        }
        let probe = this.top;
        for (let i = 0; i < this.length; i++) {
            console.log(probe.value);
            probe = probe.next
        }
    }
}

El reto

pop() {
        if(this.length === 0) {
            this.top = null;
            this.bottom = null;
        } else {
            this.top = this.top.next
        }
        this.length--;
        return this
    }```
class Node {
    constructor(value){
        this.value = value;
        this.next = null;
    }
}

class Stack {
    constructor(){
        this.top = null;
        this.bottom = null;
        this.length = 0;
    }

    peek(){
        return this.top;
    }

    push (value){
        const newNode = new Node(value);

        //validacion

        if (this.length === 0) {
            this.top = newNode;
            this.bottom = newNode;
        }else {
            const holdingPointer = this.top;
            this.top = newNode;
            this.top.next = holdingPointer;
        }

        this.length++;

        return this;
    }

    pop(){
        if (!this.length){
            console.error("No nodes in the stack");
            return;
        }

        const topNode = this.top;

        if(this.length === 1){
            this.top = null;
            this.bottom = null;
        }else {
            this.top = this.top.next;
        }
        this.length--;
        return topNode;
    }
}

const myStack = new Stack();

Aquí esta mi código del desafío, espero sus feedbacks guys.

pop() {
      if (this.length <= 1) {
        console.log("You haven't elements anymore.");
        this.bottom = null;
        this.top = null;
      } else {
        this.top = this.top.next;
        if (this.length === 1) {
          this.top = this.bottom;
          this.top = this.top.next;
        }
      }
      this.length--;
      return this;
    }

Así queda mi actividad con el método pop() 😄

pop() {
    const node = this.top;

    if (this.length === 0) {
      return "Error: Stack empty.";
    } else if (this.length === 1) {
      this.top = node.next;
      this.bottom = null;
      this.length--;
    } else {
      this.top = node.next;
      this.length--;
    }

    return this;
  }

Yo realize dos validaciones, si no existe ningun nodo y si solo existe uno solo, Saludos ;p

class Stack {
   constructor() {
      this.top = null;
      this.bottom = null;
      this.length = 0;
   }

   peak() {
      return this.top;
   }

   push( value ) {
      const newNode = new Node( value );

      if(this.length === 0) {
         this.top = newNode;
         this.bottom = newNode;
      } else {
         const holdingPointer = this.top;
         this.top = newNode;
         this.top.next =  holdingPointer;
      }

      this.length++;

      return this;
   }

   pop() {
      if( this.length === 0 ) {
         return this;
      }
      if( this.length === 1 ) {
         this.top = null;
         this.bottom = null;
         this.length = 0;
      } else {
         const holderPointer = this.top;
         this.top = holderPointer.next;
         this.length--;
      }
   return this;
   }
}

Implementación pero en Kotlin, saludos!
Stack.kt

pop() {
        if(this.length === 0) {
            return  `No hay datos en el stack`;
        } else if(this.length === 1) {
            this.top = null;
            this.bottom = null;
        } else {
            this.top = this.top.next;
        }
        this.length--;
        return this;
}

Comparto mi solución al reto 😄 Lo hice recorriendo el stack, no sé si esta sea la mejor forma, pero funcionó xd

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class Stack {
  constructor() {
    this.top = null;
    this.bottom = null;
    this.length = 0;
  }

  push(value) {
    const newNode = new Node(value);

    if (!this.bottom) {
      this.bottom = newNode;
      this.top = newNode;
      this.length++;

      return this;
    }

    this.top.next = newNode;
    this.top = newNode;

    this.length++;

    return this;
  }

  peek() {
    return this.top;
  }

  walkStack() {
    let counter = 0;
    let length = this.length - 2;
    let currentNode = this.bottom;

    while (counter !== length) {
      currentNode = currentNode.next;
      counter++;
    }

    return currentNode;
  }

  pop() {
    if (this.length === 0) {
      return console.log("El Stack ya está vacio");
    }

    if (this.length === 1) {
      const nodeToPop = this.top;
      this.top = null;
      this.bottom = null;
      this.length--;
      return nodeToPop;
    }

    const nodeToPop = this.top;
    const newTop = this.walkStack();
    this.top = newTop;

    this.length--;

    return nodeToPop;
  }
}

![](

Desafío terminado!!

**Metodo pop**
pop() {
        if(this.length == 0) {
            this.top = null;
            this.bottom = null;
        } else {
            this.top = this.top.next;

            this.length--;

            return this
        }
    }
}

Este es mi parte

pop(){
        switch (this.length) {
            case 0:
                return console.log('there isn´t stack')
            case 1:
                this.top = null;
                this.bottom = null;
                break;
            default:
                this.top = this.top.next;
                break;
        }
        this.length--;
        return this;
    }
pop() {
    if (!this.top) {
      return null;
    }
    if (this.top === this.bottom) {
      this.bottom = null;
    }
    this.top = this.top.next;
    this.length--;

    return this;
  }```

Implementacion del metodo pop():

  pop(){
    const prevTop = this.top;
    if(prevTop.next){
      this.top = this.top.next;
    } else {
      this.top = null;
      this.bottom = null;
    }
    this.length--;
    return prevTop;
  }

Ahí dejo mi implementación del método pop:

    pop( ) {

        const topNode = this.top

        if( this.length > 0){
            this.top = this.top.next
            this.length -= 1
        } 
        if( this.length === 0)
            this.bottom = null
        
        return topNode
    }

Como curiosidad podéis probar lo que pasa si se cambia el orden en la primera línea del if:

    pop( ) {

        const topNode = this.top

        if( this.length > 0){
            this.top.next = this.top
            this.length -= 1
        } 
        if( this.length === 0)
            this.bottom = null
        
        return topNode
    }
pop() {
    if (this.length === 0) {
      console.error('Empty Stack')
      return;
    }
    const topNode = this.top;
    this.top = this.top.next;
    this.length--;
    return topNode; 
  }

Así implementé el método pop

	pop() {
		if (this.length === 0) {
			return this;
		}

		this.top = this.top.next;
		this.length--;

		if (this.length === 0) {
			this.bottom = null;
		}
		return this;
	}

Me ha gustado mucho este curso, aprendemos de Estructuras de Datos y de una vez realizamos la implementación. Esta Genial. 🚀

aca esta mi codigo para el pop

pop() {
    if (this.length !== 0) {
      let courrentNode = this.top

      for (let i = 1; i < this.length - 1; i++) {        
        courrentNode = courrentNode.next
      }
      this.length--

      if (this.length === 0) {
        this.top = null
        this.bottom = null
      } else {
        courrentNode.next = null
        this.bottom = courrentNode
      }
    }

    return this
  }

Buenas noches, aporto mi respuesta

class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

class Stack {
    constructor() {
        this.top = null;
        this.bottom = null;
        this.length = 0;
    }

    peek() {
        return this.top;
    }

    push(value) {
        const newNode = new Node(value);
        if (this.length === 0) {
            this.top = newNode;
            this.bottom = newNode;
        } else {
            const holdingPointer = this.top;
            this.top = newNode;
            this.top.next = holdingPointer;
        }
        this.length++;
        return this;
    }

    pop() {
        if (this.length === 0) {
            throw new Error('There are doesn\'t nodes in the stack')
        }
        const holdingPointer = this.top.next;
        this.top = holdingPointer;
        this.length--;
        return this;
    }
}

Muy buenas estas clases he aprendido mucho, dejo la solución


class Node {
    constructor(value){
        this.value = value;
        this.next = null;
    }
}
class Stack{
    constructor(){
        this.top = null;
        this.bottom = null;
        this.length = 0;
    }
    peek(){
        return this.top;
    }
    push(value){
        const newNode = new Node(value);
        if (this.length === 0) {
            this.top = newNode;
            this.bottom = newNode;
        } else {
            const holdingPointer = this.top;
            this.top = newNode;
            this.top.next = holdingPointer;
        }
        this.length++;
        return this;
    }
    pop(){
        if( this.length === 0 ){
            console.error('No hay elementos en el stack');
            return this;
        }else if( this.length === 1 ){
            this.bottom = this.top.next;
        }
        this.top = this.top.next;
        this.length--;
        return this;
    }
}

const myStack = new Stack();
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.pop();

del reto

Aca mi solucion al metodo pop:

Mi solución al stack, removí el parámetro de bottom, ya que en mi opinión, este no debería ir, ya que va en contra de la filosofía de la pila, solo se va a utilizar el ultimo valor ingresado, por lo que bottom es información irrelevante

class Node {
    constructor(value){
        this.value = value;
        this.next = null;
    }
    setNext(next) {
        this.next = next
    }
    getNext() {
        return this.next
    }
}

class Stack {
    constructor(){
        this.top = null;
        this.length = 0;
    }
    peek(){
        return this.top
    }
    push(value){
        const newNode = new Node(value)
        if (this.length === 0) {
            this.top = newNode
        } else {
            const holdingPointer = this.top
            this.top = newNode
            this.top.setNext(holdingPointer)
        }
        this.length++
        return this;
    }
    pop() {
        if (this.length === 0) {
            console.log('No hay nodos para remover');
        } else {
            this.top = this.top.getNext()
            this.length--
            return this;
        }
    }
}

Les comparto mi codigo del metodo pop 😃


pop()                   //Metodo para desapilar el ultimo Nodo apilado
    {
        const holdingPointer = this.top.next;
        this.top = holdingPointer;
        this.length--;
        return this;
    }

Mi forma de resolverlo:

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class Stack {
  constructor() {
    this.top = null;
    this.bottom = null;
    this.length = 0;
  }

  peek() {
    return this.top.value;
  }

  push(value) {
    const newNode = new Node(value);
    this.length === 0 ? (this.bottom = newNode) : (this.top.next = newNode);
    this.top = newNode;
    this.length++;
  }

  pop() {
    let curretNode = this.bottom;
    for (let i = 0; i < this.length - 2; i++) {
      curretNode = curretNode.next;
    }
    this.top.value = null;
    this.top = curretNode;
    this.top.next = null;
    this.length--;
  }
}

export default Stack;```

Estuve viendo muchas soluciones en la caja de comentarios donde falta asignarle el valor a this.top, este no tendria que quedar en null sino que tendria que tener el mismo valor de el nodo que viene atras.

Reto completado!! 😄

A mi me pareció que la mejor forma de impementar esta estructuras de datos es con arrays, yo lo hice Así:


class Stack {
    constructor() {
        this._data = []
        this.length = this._data.length
    }
    push(value) {
        return this._data.push(value);
    }
    pop() {
       return this._data.shift();
    }
    peek() {
        return this._data[0];
    }
}

const myStack = new Stack()```

Realizando el metodo de pop en base a objetos como lo hizo el profesor: lo hice de la siguiente forma:



function Element(value) {
this.next = null
this.value = value
}

class StackMethod2 {
constructor() {
this.top = null
this.bottom = null
this.length = 0
}
peek() {
return this.top
}
push(value) {
const newElemt = new Element(value)
if (this.length === 0) {
this.top = newElemt
this.bottom = newElemt

    }else {
        newElemt.next = this.top
        this.top = newElemt
    }

    this.length ++;
    return this.length;
}
pop() {
    if(this.length === 0 || !this.top) return undefined;
    const elemtDeleted = this.top
    const elementsNext = this.top.next
    delete this.top
    this.top = elementsNext

    return elemtDeleted;
}

}

const stackYJ = new StackMethod2()

MI NOTES FOR BUILDING A STACK

class Nodo{

  constructor(value){

    this.value = value;
    this.next = null;

  }

}


class Stack{

  constructor(){
    
    this.top = null;
    this.bottom = null;
    this.length = 0;


  }
  //Para seleccionar un elemento y este elemento siempre es el elemento que esta
    //al inicio que es el ultimo en entrar y el primero en salir
  peek(){

  return this.top;

  }

  push(value){

  //Instanciamos la clase nodo para poder crear un nodo
  const newNode = new Nodo(value);

  //Validamos que el stack este vacio 
    //Si el stack esta vacio que me agregue el valor el neuevo nodo
      //A el top y tambien como ultimo valor tambien se le asigne mi nuevo nodo
  if(this.length === 0){
    this.top = newNode;
    this.bottom = newNode;

    //Si no se cumple la condicion (quiere decir que el stack no esta vacio)
    //Entonces lo que hacemos es  que le asigne al top un nuevo nodo
    //Y el siguiente valor a este sea el top que etaba anteriormente
  }else{
    const holdingPointer = this.top;
    this.top = newNode;
    this.top.next = holdingPointer;
  }
  
  this.length++;

  return this;

  }

  pop(){

  }


}```

pop():

Mi solución al reto del pop

 pop() {
    if (this.length === 1) {
      this.top = null;
      this.button = null;
    } else if (this.length === 0) {
      return null;
    } else {
      this.top = this.top.next;
    }
    this.length--;
    return this;
  }

Este es mi me todo pop(), no me cuadra la parte de las dos validaciones, si alguien tiene una forma de mejorarlo, estaré atento. 👍

pop() {
        if (this.length === 0) {
            return this;
        }
        this.top = this.top.next;
        this.length--;
        if (this.length === 0) {
            this.bottom = null;
        }
        return this;
    }

Este fue mi codigo

poop(){
        if(this.length === 1){
            this.top = this.top.next;
            this.bottom = null;
            this.length--;
        }else if(this.length === 0){
            return "La pila no tiene nodos";
        }else{
            this.top = this.top.next;
            this.length--;
        }
    }

Mi solución;

    pop(){
        if(this.length===0){
            return null;
        }
        else{
         this.top = this.top.next;
         this.length--;
        }
    }

El método pop() lo hice de la siguiente manera:

  pop() {
    if (this.length === 0) {
      return "Is not possible removes last item because this stack length is 0";
    }
    const holdingPointer = this.top.next;
    this.top = holdingPointer;
    this.length--;
    if (this.length === 0) {
      this.bottom = null;
    }
    return this;
  }

Comparto mi solución 😄

Yo hice le método pop(); asi:*

pop() {
        if(this.lenght >= 1) {
            const lastItem = this.top;
            delete this.top;

            this.lenght--;
            return lastItem;
        } else return this;
    }```

Mi implementación.

class Node {
    constructor(value){
        this.value = value;
        this.next = null;
    }
}
class Stack {
    constructor() {
        this.top = null;
        this.length = 0;
    }
    peek() {
        return this.top;
    }
    push(value) {
        const newNode = new Node(value);
        if(this.length === 0){
            this.top = newNode;
        }else{
            newNode.next = this.top;
            this.top = newNode;
        }
        this.length++;
        return this;
    }
    pop(){
        if(this.length > 0){
            this.top = this.top.next;
            this.length--;
            return this;
        }
        return undefined;
    }

}

const myStack = new Stack();

Cabe aclarar que nunca vuelvo a reasignar null al this.top porque no es necesario, de igual manera en mi implementación de mi stack el this.bottom no existe debido a que no se realiza ninguna operación con esta variable, de hecho por definición de una pila no debe existir esa variable.

Reto cumplido

    pop(){
        if (this.length === 0){
            console.log("El stack está vacío");
        } else {

            if(this.length === 1){
                this.top = null;
                this.bottom = null;
            }else{
                const holdingPointer = this.top.next;
                this.top = holdingPointer;
            }

            this.length--;
            return console.log(this);
        }
    }

Les comparto mi código, implementé varias validaciones para pulirlo

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class Stack {
  constructor() {
    this.top = null;
    this.bottom = null;
    this.length = 0;
  }
  push(value) {
    const newNode = new Node(value);
    if(this.length === 0) {
      this.top = newNode;
      this.bottom = newNode;
    } else {
      const holdingPointer = this.top;
      this.top = newNode;
      this.top.next = holdingPointer;
    }
    this.length++;
    return this;
  }
  pop() {
    if(this.length === 0) {
      return new Error("There aren't stored nodes to remove")
    }
    this.top = this.top.next;
    if(this.length === 1) {
      this.bottom = this.top;
    }
    this.length--;
    return this;
  }
  peek() {
    if(this.length === 0) {
      return new Error("There aren't stored nodes to display")
    }
    return this.top;
  }
}

const myStack = new Stack();
// Método pop()
pop() {
    this.top = this.top.next;
    this.length--;

    return this;
}

Saludosss

Implementación del método pop. Tomando en cuenta los casos de usos:



  • stack vacio
  • stack con un elemento
  • stack con varios elementos.
    pop() {
        if (this.length === 0) {
            console.log('No existen valores en el stack')
        } else {
            this.top = this.top.next
            this.length--    
        }
        return this
    }

Solución al reto de pop()

Inspirandome en el método de clases pasadas de getIndex()

  pop() {
  if(this.length <= 0) {
    return console.error('There are no nodes in the stack')
  }
  const nodeBeforeTop = this.getOneBeforeTop()
  const nodeToRemove = nodeBeforeTop.next
  delete nodeBeforeTop.next
  this.top = nodeBeforeTop
  this.length--
  return nodeToRemove
  }
  getOneBeforeTop() {
  let counter = 1
  let currentNode = this.bottom
    while (counter !== this.length - 1) {
      currentNode = currentNode.next
      counter++
    }
  return currentNode
  }

Mi metodo pop.

 pop(){
        const topNode = this.top;
        if(this.length === 0){
            console.log('NO EXISTEN NODOS EN EL STACK');
        }else{
           this.top = this.top.next;
        }
        this.length--;
        return topNode;
    }```

Mi solucion al metodo pop 😃

pop() {
        // eliminar el ultimo elemento. (el de hasta arriba)
        if (this.length === 0) {
            // cuando no hay elementos.
            return "The stack is empty.";
        } else if (this.length === 1) {
            // cuando solo hay un elemento.
            this.top = null;
            this.bottom = null;
        } else {
            const holdingPointer = this.top.next;
            this.top = null;
            this.top = holdingPointer;
        }
        this.length--;
        return this;
    }```

Compañeros les comparto mi solución del reto, espero les guste.

pop() {
    if(this.length === 0) {
      console.error('El Stack está vacío, no hay elementos para eliminar');
    } else {
      const deleteNode = this.top;
      this.top = deleteNode.next;
    }
    this.length--;
    return this;
  }

Asi me salio hacerlo 😃 si tienen alguna correccion los leo

`pop(){
if(this.length === 0) return ‘No elements in the stack’

    const element = this.peek();
    const newTop = element.next;
    this.top = newTop;
    this.length-- 

    return element.value + ' eliminated'
}

}`

const newStack = new Stack();

Esta fue mi solución:

    pop(){
        if (this.length === 0){
            console.log('No elements to pop.');
            return null;
        }
        const holdingPointer = this.top;
        if (this.length === 1){
            this.bottom = null;
            this.top = null;
        } else {
            this.top = this.top.next;
        }
        this.length--;
        return holdingPointer;
    }

Adjunto mi aporte del método POP():

 pop() {
        if(this.length === 0) {
            console.log('The stack is empty');
        } else if (this.length === 1) {
            this.top = null;
            this.bottom = null;

            this.length--;
        } else {
            this.top = this.top.next;

            this.length--;
        }

        return this;
    }

Les comparto el código que hice para el stack aquí:

pop() {
    this.length > 0 ? this.length-- : undefined;
    return this.top = this.top?.next;
  }

Para poder hacer el método pop en una estructura Stack , lo solucioné hallando el penúltimo elemento y asignarlo al this.top, disminuyo el length en 1 y listo.

pop() {
    var penultimo = myStack.bottom;
    //El sgt loop también es válido para stacks con 1 o 2 valores(simplemente no ejecuta los statements que están dentro)
    for(let i = 0; i < this.length-2; i++) {
      penultimo = penultimo.next;
    }
    this.top = penultimo;
    this.top.next = null;
    this.length--;

    return this;
  }
class Node{
  constructor(value){
    this.value = value;
    this.next = null;
  }
}

class Stack{
  constructor(){
    this.top = null;
    this.bottom = null;

    this.length = 0;
  }

  peek(){
    return this.top;
  }

  push(value){
    const newNode = new Node(value);

    if(this.length === 0){
      this.top = newNode;
      this.bottom = newNode;
    } else {
      // const pointer = this.top;
      // this.top = newNode;
      // this.top.next = pointer;
      newNode.next = this.top;
      this.top = newNode;
    }

    this.length++;
    return this;
  }

  pop(){
    const item = this.top;

    if(this.length === 1){
      this.top = null;
      this.bottom = null;
      this.length--;
      return item;
    }else if(!this.length){
      return undefined;
    }

    this.top = this.top.next;
    this.length--;
    return item;
  }
}

const stack = new Stack();```
pop () {
    if (this.length <= 1) {
      this.top = null;
      this.bottom = null;
      this.length = 0;
      console.log("El stack está vacio");
    } else {
      this.top = this.top.next;
      this.length--;
    }
  }

Mi implementacion del metodo pop():

  pop() {// Método para eliminar el ultimo metodo
    if (this.lenght === 0) {
      return `No hay elementos para eliminar`;
    } else {
      const topNode = this.top;
      if (this.lenght === 1) {
        this.top = null;
        this.bottom = null;
      } else {
        this.top = this.top.next;
      }
      this.lenght--;
      return topNode;
    }
  }```

Mi código método pop

  pop(){
    if(this.length === 0){
      return
    }
    if(this.length === 1){
      this.top = null
      this.bottom = null
      this.length = 0;
      return
    }
    const holdingPointer = this.top.next
    this.top = holdingPointer
    this.length--
  }
}