【问题标题】:How to return the number of elements in a linkedlist如何返回链表中的元素数
【发布时间】:2019-11-05 06:55:54
【问题描述】:

我需要实现 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() 函数不需要。这是我的第一堂编程课,所以我希望我提供了解决这个问题所需的一切。请帮忙enter image description here

【问题讨论】:

标签: java linked-list stack element


【解决方案1】:

类似的东西会计算元素:

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

【讨论】:

    猜你喜欢
    • 2021-09-05
    • 2013-12-01
    • 1970-01-01
    • 2021-02-07
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多