簡體   English   中英

如何返回鏈表中的元素數

[英]How to return the number of elements in a linkedlist

我需要實現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列表=新的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 ) );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM