首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何打印堆栈中的最后一项?(使用飞镖)

如何打印堆栈中的最后一项?(使用飞镖)
EN

Stack Overflow用户
提问于 2022-10-25 08:13:13
回答 1查看 40关注 0票数 0
代码语言:javascript
复制
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’定义运算符'[]‘”。如何控制堆栈中的索引。我只想在屏幕上打印“额外的印版”。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-25 08:17:49

如果使用构建的函数可以获得最后一个元素,则不需要使用该结构plates[plates.length-1]。如果要在Custom Stack中获取最后一项,可以在Custom Stack中定义一个函数。

T get peek => _list.last;

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74190954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档