簡體   English   中英

在通用堆棧類中創建通用堆棧

[英]Creating a generic stack in generic stack class

我試圖自學一些Java,並且遇到了似乎很簡單的問題,但是我仍然找不到解決方案。

到目前為止,我有:

接口:

public interface ADTStack<T> {


public boolean isEmpty();


public void push(T element);


public T top() throws IllegalStateException;


public void pop() throws IllegalStateException;
}

類堆棧:

public class Stack<T> implements ADTStack<T> {

private java.util.LinkedList<T> data;  



public Stack() {
    data = new java.util.LinkedList<T>();
}

@Override
public boolean isEmpty() {
    return data.isEmpty();
}

@Override
public void push(T element) {
    data.add(0, element);
}

@Override
public T top() throws IllegalStateException {
    if (isEmpty()) {
        throw new IllegalStateException("Stack is emtpy.");
    }
    return data.getFirst();
}

@Override
public void pop() throws IllegalStateException {
    if (isEmpty()) {
        throw new IllegalStateException("Stack is empty.");
    }
    data.remove(0);
}

好了,這就是我想要做的。 我試圖寫一個方法equals比較兩個堆棧。 我的想法是使用第三個堆棧,以便在比較它們之后將兩個堆棧都恢復為原始狀態。

這是我所擁有的:

    Stack supportStack = new Stack();

public boolean equals(ADTStack<T> s){
    if (data.isEmpty() != s.isEmpty()){         
        return false;
    }
    if (data.isEmpty() && s.isEmpty()){     
        return true;
    }

    T element_a  =  this.top();             
    T element_b  = s.top();


    if( (element_a ==null && (element_b !=null) || !element_a.equals(element_b) || element_a != null && element_b == null)){
        return false;
    }

    data.pop();
    s.pop();                        
    supportStack.push(element_a);       
    boolean result = data.equals(s);    

    while (!supportStack.isEmpty()){        
        data.push(supportStack.top());   
        s.push(supportStack.top());
        supportStack.pop();
    }
    return result;                      
}

編譯代碼時出現很多錯誤,似乎有些問題:

Stack supportStack = new Stack();

我真的不知道怎么了以及如何解決錯誤。 我做了一個跑步者班,嘗試了構造函數,它起作用了,所以我對什么地方感到困惑。

public class Runner {

   public static void main(String[] args){
      Stack test = new Stack();
      test.push(12);
      System.out.println(test.top());
   }
}

自從我自學以來,我很樂意接受任何建議或建設性的批評,如果有什么不清楚的地方,請隨時提出。

Stack supportStack = new Stack();

Stack被稱為原始類型 :就像不使用泛型一樣。 您需要使用:

Stack<T> supportStack = new Stack<T>();

但是,提示:您不需要這樣做。 您可以這樣做:

return this.data.equals( s.data );

暫無
暫無

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

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