如何从堆栈中删除特定元素?

时间:2016-02-03 19:04:32

标签: java stack

我试图接受要删除的元素的输入并弹出堆栈中的所有元素。

String[] colors={"Red","Green","White","Yellow","Blue"};
Scanner sc=new Scanner(System.in);
Stack<String> stack=new Stack<String>();

void push(){
        System.out.println("Stack after all the elements are pushed is");

        for(int i=0; i<12; ++i){
            //defining a random element to be pushed into the stack
            int rnd=new Random().nextInt(colors.length);
            //pushing the element into the stack
            stack.push(colors[rnd]);
            if(i>11)
                break;
            //displaying all the elements present in the stack. 
            System.out.println(stack.get(i));
        }

}

void pop(String str){
    System.out.println("Enter the Color to be removed");

    while(!stack.empty()) {

        System.out.println("Element removed is "+stack.pop());

    }   


}

主程序

public static void main(String[] args) throws StackOverflowError {
    StackExample obj=new StackExample();
    obj.push();
    obj.display();

    Scanner sc= new Scanner(System.in);
    String s= sc.next();
    obj.pop(s);
    obj.display();
}

1 个答案:

答案 0 :(得分:0)

我会在这里试着回答你的问题。我不明白这里有一系列颜色。我也没有得到使用堆栈的意义。我会使用堆栈,因为这就是你要求的。

看起来像是一个家庭作业问题。因此,我会尝试指出正确的方向,而不是为您写出解决方案。

假设您有一个包含输入颜色的String数组。

String[] colors = {"Black", "Green", "Blue", "Black"};

您将使用的堆栈声明为: Stack<String> stack = new Stack<String>();

让我们将所有颜色输入到这个堆栈中:

for(String color: colors)
    stack.push(color);

Stack以后进先出的方式工作。假设我们必须从堆栈中删除"Black"。在此操作之后,堆栈应如下所示:["Blue", "Green"]。一种方法是使用辅助堆栈来存储我们想要保留的所有元素,并丢弃我们不需要的元素。

String compareString = "Black";
Stack<String> auxStack = new Stack<String>();
while(!stack.isEmpty()) {
    String st = stack.pop();
    if(st.compareTo(compareString) != 0)
        auxStack.push(st);
}

while(!auxStack.isEmpty()) 
    stack.push(auxStack.pop());

这应该指向正确的方向。如果您有任何问题,请告诉我。