辍学堆栈无效

时间:2016-09-11 21:26:58

标签: java stack push pop

我正在尝试创建一个程序,当堆栈已满时(例如可以保存5个值),并且您尝试在堆栈上推送另一个值,它执行DropOut方法。套装在哪里。堆叠在位置0到位置1等....一直到位置3 ==到位置4.从这里我想删除堆栈上的顶部值(在这个例子中它是位置4的值(第五个值) ))从这里我可以将我的下一个值添加到堆栈顶部....但我的代码没有按预期工作。我是初学者,感谢任何可用的输入。谢谢你的时间。

package jsjf;

 import jsjf.exceptions.*;
 import java.util.Arrays;
 import java.util.*;


public class ArrayStack1<T> implements StackADT<T>
{
     private final static int DEFAULT_CAPACITY = 5;

     private int top;  
     private T[] stack;
     private int next;

 public ArrayStack1()
    {
        this(DEFAULT_CAPACITY);
}


public ArrayStack1(int initialCapacity)
{
    top = -1;
    stack = (T[])(new Object[initialCapacity]);


}


   public void push(T element)
{

  if (top+1==DEFAULT_CAPACITY){
    DropOut();
    //top=top-1;
    pop();
    stack[top]=element;
  }
  top++;
  stack[top] = element;

}



    public void DropOut(){

    for (int x=0; x<stack.length-1; x++){
     // if(x==stack.length){
     // stack[x]=null;
     // }
        stack[x]=stack[x+1];
    }


     }

  public T pop() throws EmptyCollectionException
{
    if (isEmpty())
        throw new EmptyCollectionException("stack");


    T result = stack[top];
    stack[top] = null; 

    return result;
}


   public T peek() throws EmptyCollectionException
{
    if (isEmpty())
        throw new EmptyCollectionException("stack");

    return stack[top];
}


  public boolean isEmpty()
{
  return (top < 0);
}


public int size(){
return (top+1);
}



   public String toString()
{
  String result = "";

    for (int scan=0; scan <= top; scan++) 
    result = result + stack[scan].toString() + "\n";

  return result;
}

 public static void main(String[] args) { 

  ArrayStack1<Integer> t1=new ArrayStack1<Integer>(5);
  t1.push(5);
  t1.push(3);
  t1.push(6);
  t1.push(5);
  t1.push(3);//
  t1.push(4);

}
}

1 个答案:

答案 0 :(得分:0)

push上,当您达到最大容量时,您将堆叠元素两次。 else应解决您的问题:

public void push(T element)
{

    if (top+1==DEFAULT_CAPACITY){
        DropOut();
        //top=top-1;
        pop();
        stack[top]=element;
    } else {
        top++;
        stack[top] = element;
    }
}