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;
int get length => _list.length;
@override
String toString() => _list.toString();
}
void main() {
CustomStack<String> plates = CustomStack();
//Add plates into the stack
plates.push("Plate1");
plates.push("Plate2");
plates.push("Plate3");
plates.push("Plate Extra");
print(plates);
print(plates[plates.length-1]);
}我在最后一行中看到了一个错误:“未为类型‘CustomStack’定义运算符'[]‘”。如何控制堆栈中的索引。我只想在屏幕上打印“额外的印版”。
发布于 2022-10-25 08:17:49
如果使用构建的函数可以获得最后一个元素,则不需要使用该结构plates[plates.length-1]。如果要在Custom Stack中获取最后一项,可以在Custom Stack中定义一个函数。
T get peek => _list.last;
https://stackoverflow.com/questions/74190954
复制相似问题