How to implement a stack with push and pop in Dart
The code from the stack package was helpful. Here is a simplified version:
class Stack<T> { final _stack = Queue<T>(); void push(T element) { _stack.addLast(element); } T pop() { final T lastElement = _stack.last; _stack.removeLast(); return lastElement; } void clear() { _stack.clear(); } bool get isEmpty => _stack.isEmpty;}
Notes:
A
Queue
allows you to modify both ends and is by default aListQueue
. See this question for more info about that.Pushing is adding to the queue and popping is removing the last element and then returning that element.
You could also add a
top
getter to see what the last element is without popping it.
Usage
You can use it like this now:
final myStack = Stack<int>();myStack.push(1);final top = myStack.pop();
here is the class I use
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;}
My version of a Queue wrapper:
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);}