java - 如何返回链表中的元素数
问题描述
我需要实现 size() 函数,以便计算列表中元素的数量。
我不能使用计数变量。应该可以工作(给定我们的“顶部”节点和构造函数 [默认] 设置)。我知道我必须使用循环,但我不知道如何像使用数组一样引用索引。
public class DropOutStack<T> implements StackADT<T> {
private int max;
private LinearNode<T> top;
public DropOutStack(){
max = 10;
top = null;
}
public DropOutStack(int capacity){
setMaxSize(capacity);
}
public DropOutStack(T element){
LinearNode<T> temp = newLinearNode(element);
temp.setNext(top);
top = temp;
max = 10;
}
public DropOutStack(T element, int capacity){
LinearNode<T> temp = newLinearNode(element);
temp.setNext(top);
top = temp;
setMaxSize(capacity);
}
public int size(){
}
public boolean isEmpty(){
if(top == null) return true;
return false;
}
}
DropOutStack list = new DropOutStack("T",4);
System.out.print(list.size());
应该打印 1。因为只添加了“T”。
添加合成类的屏幕截图。我想我必须从那里使用一种方法。接口只是声明了 push pop peek isempty 函数。没有代码。我相信 size() 函数不需要。这是我的第一堂编程课,所以我希望我提供了解决这个问题所需的一切。请帮助在此处输入图像描述
解决方案
类似的东西会计算元素:
ToIntFunction<LinearNode<T>> counter = (node) -> {
int count = 0;
while( node != null ) {
count++;
node = node.getNext();
}
return( count );
};
…应用于 DropOutStack 类 size() 函数:
public int size() {
return( counter.applyAsInt( top ) );
}
推荐阅读
- angular - 在 Angular 中使用 Momentjs 查找本周的日期
- asp.net - 如何在 Asp.Net 界面上显示 ckeditor 值
- python - 变量更改不会在第二个文件上更新
- laravel - 在 Laravel 中调用的 Docker 容器
- python - 如何在 Flask api 中从控制器导入模型
- playwright - 如何处理剧作家中的负面测试用例
- python - How do i fix: TypeError: cannot unpack non-iterable NoneType object?
- javascript - inline an input and set its width to fit the content in CSS or jQuery
- python - python代码 - 用特殊分隔符分割路径
- excel - 从 Outlook 365 自动保存附件