首页 > 解决方案 > 通过调整堆栈大小来实现堆栈

问题描述

我试图使用 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());      
    
}

}

标签: data-structuresdynamicstack

解决方案


top您应该像推送到堆栈时一样更新您的变量。

public int pop()
{

    return stack[top--];
}

推荐阅读