Cómo implementar una pila con push y pop en Dart

Sep 25 2020

Me gustaría implementar una estructura de datos de pila (que no debe confundirse con el widget Flutter Stack) en Dart para poder manejar una pila de TextStyles personalizados para la representación de texto de Flutter.

Sé que con la pila puedes empujar y sacar valores. Esto suena similar a Queue, pero no estoy seguro de la diferencia.

Esto no funciona:

final myStack = Queue<int>();
myStack.push(1);
final top = myStack.pop();

Respuestas

2 Suragch Sep 25 2020 at 15:55

El código del paquete de pila fue útil. Aquí hay una versión simplificada:

class Stack<T> {
  final _stack = Queue<T>();

  void push(T element) {
    _stack.addLast(element);
  }

  T pop() {
    T lastElement = _stack.last;
    _stack.removeLast();
    return lastElement;
  }
}

Notas:

  • A le Queuepermite modificar ambos extremos y por defecto es a ListQueue. Consulte esta pregunta para obtener más información al respecto.

  • Empujar es agregar a la cola y hacer estallar es eliminar el último elemento y luego devolver ese elemento.

  • También puede agregar un topcaptador para ver cuál es el último elemento sin hacer estallarlo.

Uso

Puedes usarlo así ahora:

final myStack = Stack<int>();
myStack.push(1);
final top = myStack.pop();
1 alirezaeasazade Oct 13 2020 at 21:21

aquí está la clase que uso

import 'dart:collection';

class Stack<T> {
  final _stack = Queue<T>();

  int get length => _stack.length;

  bool canPop() => _stack.isNotEmpty;
  
  void clearStack(){
    while(_stack.isNotEmpty){
      _stack.removeLast();
    }
  }

  void push(T element) {
    _stack.addLast(element);
  }

  T pop() {
    T lastElement = _stack.last;
    _stack.removeLast();
    return lastElement;
  }

  T peak() => _stack.last;

}
theanurin Dec 10 2020 at 06:27

Mi versión de un contenedor de cola:

import "dart:collection" show Queue;

class Stack<T> {
  final Queue<T> _underlyingQueue;

  Stack() : this._underlyingQueue = Queue<T>();

  int get length => this._underlyingQueue.length;
  bool get isEmpty => this._underlyingQueue.isEmpty;
  bool get isNotEmpty => this._underlyingQueue.isNotEmpty;

  void clear() => this._underlyingQueue.clear();

  T peek() {
    if (this.isEmpty) {
      throw StateError("Cannot peek() on empty stack.");
    }
    return this._underlyingQueue.last;
  }

  T pop() {
    if (this.isEmpty) {
      throw StateError("Cannot pop() on empty stack.");
    }
    return this._underlyingQueue.removeLast();
  }

  void push(final T element) => this._underlyingQueue.addLast(element);
}