通过调整堆栈大小来实现堆栈



我试图使用java实现一个堆栈,调整堆栈大小。我的代码是正确的,它运行得很好,但在从堆栈中弹出元素后,当我再次调用peek函数时,相同的元素显示在堆栈的顶部。显示我应该做哪些更改以使我的代码正确。

class DynamicStack
{
private int stack[];
private int stackSize;
private int top ;
DynamicStack()
{
stackSize = 1;
top = -1;
stack = new int[stackSize];
}
public int isEmpty()
{
if(top == -1)
{
System.out.println("Stack is empty");
}
return 0 ;
}
public int isFull()
{ 
if(top == stackSize-1)  
{
System.out.println("Stack is full");
}
return 0;
}
public int pop()
{
return stack[top];
}
public void push(int data)
{
if(top>=stackSize-1)
resize();
stack[++top]=data;          
}
private void resize()
{
int[] temp= stack;
stackSize = stackSize*2;
stack = new int[stackSize]; 
for(int i= 0;i<=top;i++)
{
stack[i]=temp[i];   
}
}
public int peek()
{
return stack[top];
}
public static void main(String[] args)
{
DynamicStack ds = new DynamicStack();
ds.push(12);
ds.push(13);
ds.push(2); 
System.out.println(ds.stackSize);
System.out.println(ds.peek());
System.out.println(ds.pop());
System.out.println(ds.peek());      

}

}

你应该更新你的top变量,就像你在压入堆栈时所做的那样。

public int pop()
{
return stack[top--];
}

最新更新