Come implementare uno stack con push and pop in Dart
Vorrei implementare una struttura di dati dello stack (da non confondere con il widget Flutter Stack) in Dart in modo da poter gestire una pila di TextStyles personalizzati per il rendering del testo Flutter.
So che con lo stack puoi spingere e far apparire i valori. Sembra simile a Queue, ma non sono sicuro della differenza.
Questo non funziona:
final myStack = Queue<int>();
myStack.push(1);
final top = myStack.pop();
Risposte
Il codice dal pacchetto stack è stato utile. Ecco una versione semplificata:
class Stack<T> {
final _stack = Queue<T>();
void push(T element) {
_stack.addLast(element);
}
T pop() {
T lastElement = _stack.last;
_stack.removeLast();
return lastElement;
}
}
Appunti:
A
Queueconsente di modificare entrambe le estremità ed è per impostazione predefinita aListQueue. Vedi questa domanda per maggiori informazioni a riguardo.Spingere è aggiungere alla coda e il popping è rimuovere l'ultimo elemento e quindi restituire quell'elemento.
Puoi anche aggiungere un
topgetter per vedere qual è l'ultimo elemento senza farlo scoppiare.
Utilizzo
Puoi usarlo in questo modo ora:
final myStack = Stack<int>();
myStack.push(1);
final top = myStack.pop();
ecco la classe che 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;
}
La mia versione di un wrapper Queue:
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);
}