即时在JAVA中动态实现一个堆栈,我已经到了这个问题。事情是,我的代码工作,我不知道为什么。所以这里是我的,我不明白的部分代码:参考价值复制
Node<E> newNode = new Node(elem,top);
newNode=top;
size++;
所以,我newNode的第二个参数是紧挨着它的对象,是至极顶在这种情况下。 然后我说我的newNode = top;所以,按照我的逻辑,newNode在newNode旁边,因为我在newNode = top之后的指令中说过;我在这里错过了什么?我知道它是一个愚蠢的问题:(事情是,它的工作原理,我已经看到了一些类似的实现,我只是不明白为什么它的工作原理
编辑:生病后我整个代码:
类节点:
public class Node<E> {
private E element;
private Node<E> next;
public Node(E element, Node<E> next) {
this.element = element;
this.next = next;
}
public E getElement() {
return element;
}
public void setElement(E element) {
this.element = element;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
//到此为止
接口堆栈:
public interface Stack<E> {
//numero de elementos presentes na pilha
public int size();
//nao contem elementos?
public boolean isEmpty();
//devolve proximo objecto a sair, sem remover
public E peek()
throws EmptyStackException;
//empilha novo elemento
public void push(E o)
throws FullStackException;
//desempilha proximo elemento
public E pop()
throws EmptyStackException;
}
// INTERFACE到此为止
类StackDynamic
public class StackDynamic<E> implements Stack<E>{
private int size;
private Node<E> top;
private int maxCapacity;
public StackDynamic(int capacity)
{
this.maxCapacity=capacity;
this.size=0;
this.top=null;
}
public StackDynamic()
{
this(-1);
}
@Override
public int size() {
return this.size;
}
@Override
public boolean isEmpty() {
return (this.size == 0);
}
@Override
public E peek() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException("A pilha está vazia.");
}
return top.getElement();
}
@Override
public void push(E elem) throws FullStackException {
if(size==maxCapacity){
throw new FullStackException("Está cheio");
}
**Node<E> newNode = new Node<>(elem, top);
top=newNode;
size++;** //error here
}
@Override
public E pop() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException("A pilha está vazia.");
}
E elemRemoved = top.getElement();
top = top.getNext();
size--;
return elemRemoved;
}
// CLASS到此为止
现在的newNode =顶部;命令不要让有很大的意义对我来说:S
你确定你没有在第二条语句混淆的顺序?我期望它是'top = newNode;'。 – delnan
我想我们需要更多的代码。 –