Sobes.tech
Junior — Middle

How can you create a stack data structure in Dart?

sobes.tech AI

Answer from AI

In Dart, you can implement a stack data structure using a class that utilizes a list (List) to store elements. The main operations of a stack are adding (push) and removing (pop) elements from the end of the list.

class Stack<T> {
  final List<T> _items = [];

  void push(T item) {
    _items.add(item);
  }

  T pop() {
    if (_items.isEmpty) {
      throw StateError('Stack is empty');
    }
    return _items.removeLast();
  }

  bool get isEmpty => _items.isEmpty;

  int get length => _items.length;
}

void main() {
  var stack = Stack<int>();
  stack.push(10);
  stack.push(20);
  print(stack.pop()); // 20
  print(stack.pop()); // 10
}

This class can be used to store elements of any type thanks to generics.

How can you create a stack data structure in Dart… - sobes.tech