最近、私のクラスでは ArrayLists と LinkedLists を勉強しています。先週、LinkedList スタック クラス内に push メソッドと pop メソッドを作成するよう依頼された課題を受け取りました。後入れ先出しのようなスタックの背後にあるロジックは理解していますが、実際のコードに問題があります。私はコンピューター サイエンスを始めたばかりで (これは 2 回目のコースです)、この特定の割り当ては文字通り私の髪を引っ張る原因となっています。この課題はすでに提出済みですが、来週は中間試験があるので、うまくやりたいと思っています。私は助けを求めてウェブや教科書のいたるところにいましたが、何もありませんでした。私の教授は私を TA に紹介するだけで、TA は実際のコードではなく、ロジックを支援することにのみ関心があります。私の教授が私に与えた指示と、これまでの私のコードを以下に掲載します。
教授 より:
次の Java ファイルで指定されたテンプレートを使用してスタックを実装します。
CS401StackInterface.java CS401StackLinkedListImpl.java
public interface CS401StackInterface<E>
{
/**
* Get the top element on the stack.
*
* @return the first element on the stack.
*/
public E pop();
/**
* Adds an element on the top of the stack.
*
* @param e - The element to be added to the stack.
*/
public void push(E e);
/**
* Determines the number of elements in this data structure.
*
* @return the number of elements currently resident in this
* data structure.
*/
public int size();
}
メソッドを定義しようとする実際のクラスは次のとおりです。
public class CS401StackLinkedListImpl<E> implements CS401StackInterface<E>
{
private LinkEntry<E> head;
private int num_elements;
public CS401StackLinkedListImpl()
{
head = null;
num_elements = 0;
}
public void setElement(LinkEntry<E> anElement){
head = anElement;
}
/*Append the new element to the end of the list*/
public void push(E e)
{
LinkEntry<E> temp = new LinkEntry<E>();
temp.element = e;
temp.next = head;
head = temp;
}
/*Remove the most recently pushed element at the end of the list*/
public E pop()
{
head.next = head;
num_elements--;
return (E) head;
}
public int size()
{
LinkEntry<E> temp = new LinkEntry<E>();
for (temp = head; head != null; head = head.next)
num_elements++;
return num_elements;
}
public String toString()
{
String string = "";
LinkEntry<E> temp = new LinkEntry<E>();
for (temp = head; temp != null; temp = temp.next)
{
string += temp.element.toString() + "";
}
return string;
}
/* ------------------------------------------------------------------- */
/* Inner classes */
protected class LinkEntry<E>
{
protected E element;
protected LinkEntry<E> next;
protected LinkEntry() { element = null; next = null; }
}
}
最後に、メソッドをテストするメイン クラスを次に示します。
import java.util.*;
public class App {
public static <E> void main(String[] args) {
CS401StackLinkedListImpl<String> my_stack = new CS401StackLinkedListImpl<String>();
my_stack.push("Brian");
my_stack.push("Chris");
my_stack.push("Joe");
System.out.println("Stack size: " + my_stack.size());
my_stack.pop();
System.out.println("Stack size: " + my_stack.size());
my_stack.toString();
}
}
メインクラスを実行すると、次のように返されます。
Stack size: 3
Exception in thread "main" java.lang.NullPointerException
at week6.CS401StackLinkedListImpl.pop(CS401StackLinkedListImpl.java:30)
at week6.App.main(App.java:66)
私が遭遇したものはすべて、新しいスタックを作成するように指示するだけです。これは、コードの「内部」について心配する必要がないため簡単ですが、それは私が必要としているものではありません。ありがとう。