首页 > 解决方案 > 如何返回链表中的元素数

问题描述

我需要实现 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() 函数不需要。这是我的第一堂编程课,所以我希望我提供了解决这个问题所需的一切。请帮助在此处输入图像描述

标签: javalinked-liststackelement

解决方案


类似的东西会计算元素:

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 ) );
}

推荐阅读