最近,我班一直在学习ArrayLists和LinkedLists。上周我们收到了一个任务,要求我们在 LinkedList 堆栈类中创建 push 和 pop 方法。我了解堆栈背后的逻辑,因此它是后进先出的,但我在实际代码中遇到了麻烦。我对计算机科学相当陌生(这是我的第二门课程),这个特殊的任务确实让我把头发拔了出来。我已经上交了这个作业,但我们下周有期中考试,我想好好完成它。我一直在网上和我的教科书上寻求帮助,但没有。我的教授只把我介绍给助教,助教只关心帮助我处理逻辑,而不是实际的代码。我将在下面发布教授给我的说明以及到目前为止的代码。
来自教授:
使用以下 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)
我遇到的所有事情都只是告诉我创建一个新堆栈,这很容易,因为我不必担心代码的“内部”,但这不是我需要的。谢谢。