Skip to content

Instantly share code, notes, and snippets.

@suragch
Last active October 1, 2021 01:58
Show Gist options
  • Save suragch/05cd940e6e1b4d0191becc28e2b4b941 to your computer and use it in GitHub Desktop.
Save suragch/05cd940e6e1b4d0191becc28e2b4b941 to your computer and use it in GitHub Desktop.
Stack example
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';
}
}
@suragch
Copy link
Author

suragch commented Sep 29, 2021

If your function only has one line you can use => instead of return.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment