Home > Net >  How to define a Stack in dartPad?
How to define a Stack in dartPad?

Time:10-25

https://dartpad.dev/?

import 'package:starter/stack.dart';

void main() {
print (calculation("(2 2*6"));
}

 calculation(expression){
   var tokens = expression.split(" ");
   Stack values = Stack();
   Stack ops = Stack();
}

note that if I remove the import (first line) I get this error message "The function 'Stack' isn't defined." and when I add the import the error message is "Unsupported import(s): (package:starter/stack.dart)".

CodePudding user response:

Stack is not built in the dart. But we can make a generic class with its methods(get, push, pop) implementation using list.

class CustomStack<T> {
  final _list = <T>[];

  void push(T value) => _list.add(value);

  T pop() => _list.removeLast();

  T get top => _list.last;

  bool get isEmpty => _list.isEmpty;
  bool get isNotEmpty => _list.isNotEmpty;

  @override
  String toString() => _list.toString();
}

Just put the above class somewhere in the project lib directory. And use it like.

CustomStack<String> plates = CustomStack();
//Add plates into the stack
  plates.push("Plate1");
  plates.push("Plate2");
  plates.push("Plate3");
// delete the top plate
  plates.pop();
  • Related