Last active
October 1, 2021 01:58
-
-
Save suragch/05cd940e6e1b4d0191becc28e2b4b941 to your computer and use it in GitHub Desktop.
Stack example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
final stack = Stack<int>.of([42, 12, 1000]); | |
// final stack = Stack<int>(); | |
// stack.push(42); | |
// stack.push(12); | |
// stack.push(1000); | |
final lastValue = stack.pop(); | |
final letsPeek = stack.peek(); | |
print(stack); | |
print(stack.peek()); | |
} | |
class Stack<E> { | |
// constructor | |
Stack() : _list = []; | |
// named constructor | |
Stack.of(this._list); | |
final List<E> _list; | |
void push(E item) => _list.add(item); | |
E pop() => _list.removeLast(); | |
E peek() => _list.last; | |
bool get isEmpty => _list.isEmpty; | |
@override | |
String toString() { | |
const top = '---Top---\n'; | |
final middle = _list.reversed.join('\n'); | |
const bottom = '\n---------'; | |
return '$top$middle$bottom'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If your function only has one line you can use
=>
instead ofreturn
.