【发布时间】:2017-10-07 00:50:23
【问题描述】:
所以在我的作业中,我必须在 Java 中实现一个 dropout 堆栈。退出堆栈在各方面都像堆栈一样,除了如果堆栈大小为 n,那么当 n+1 个元素被压入时,第一个元素会丢失。就我而言,我设置了 n=5。我的代码运行良好,但是当我在第 5 个元素之后添加更多元素时,底部的元素不会被删除。它只是像普通堆栈一样将新堆栈堆叠在顶部。请帮助我了解如何解决此问题。这是我的堆栈实现代码:
/**
* Represents a linked implementation of a stack.
*
* @author Java Foundations
* @version 4.0
*/
public class DropOutStack<T> implements StackADT<T>
{
private int count; //number of elements in the stack
private LinearNode<T> top;
/*Declares the maximum number of elements in the stack*/
private final int n = 5;//max size
private LinearNode<T> prev;
private LinearNode<T> curr;
/**
* Creates an empty stack.
*/
public DropOutStack()
{
count = 0;
top = null;
}
/**
* Adds the specified element to the top of this stack.
* @param element element to be pushed on stack
*/
public void push(T element)
{
LinearNode<T> temp = new LinearNode<T>(element);
/*Verifies that the number of elements in the stack is
* less than n. If yes, adds the new element to the stack*/
if (count < n) {
temp.setNext(top);
top = temp;
count++;
}
/*Verifies if the number of elements in the stack is greater
* than or equal to n or not, and that the n is not equal to one.
* If yes, removes the first element from the stack and adds
* the new element to the stack*/
else if(count>=n && n!=1) {
prev = top;
curr = top.getNext();
while(curr != null) {
prev = prev.getNext();
curr = curr.getNext();
}
prev.setNext(null);
count--;
push(element);
}
else //if n=1
{
top.setElement(element);
}
}
/**
* Removes the element at the top of this stack and returns a
* reference to it.
* @return element from top of stack
* @throws EmptyCollectionException if the stack is empty
*/
public T pop() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
T result = top.getElement();
top = top.getNext();
count--;
return result;
}
/**
* Returns a reference to the element at the top of this stack.
* The element is not removed from the stack.
* @return element on top of stack
* @throws EmptyCollectionException if the stack is empty
*/
public T peek() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
T result = top.getElement();
return result;
}
/**
* Returns true if this stack is empty and false otherwise.
* @return true if stack is empty
*/
public boolean isEmpty()
{
return (count ==0);
}
/**
* Returns the number of elements in this stack.
* @return number of elements in the stack
*/
public int size()
{
return count;
}
/**
* Returns a string representation of this stack.
* @return string representation of the stack
*/
public String toString()
{
String result = "";
LinearNode<T> current = top;
while (current != null) {
result = current.getElement() + "\n" + result;
current = current.getNext();
}
return result;
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow!看来您需要学习使用调试器。请帮助自己一些complementary debugging techniques。如果您之后仍有问题,请随时返回 Minimal, Complete and Verifiable Example 来证明您的问题。
标签: java linked-list stack