Reversing an array using a stack

∥☆過路亽.° 提交于 2019-12-12 22:09:02

问题


I am attempting to reverse an array using a stack. However, I get an error on arr[i] = stack.top();, and the suggestion to resolve it in Eclipse is to change it to arr[i] = stack.pop(); or to add a cast. Is there another way about this or have I made a mistake?

I see tutorials and questions asking about how to reverse a string using a stack and I have tried to reverse an array using the same logic, but I'm not entirely sure where I'm going wrong.

public static void reverse(String[] arr){ 

    Stack stack = new Stack();

    for(int i = 0; i < arr.length; i++) {           
        stack.push(arr[i]);

    }
    for(int i = 0; i < arr.length; i++) {
        arr[i] = stack.top();
        stack.pop();     
    }
    return;
} 

回答1:


When you pop the stack, it returns the object at the top and removes it from the stack. Try this:

public static void reverse(String[] arr){ 

    Stack stack = new Stack();    

    for(int i = 0; i < arr.length; i++) {           
        stack.push(arr[i]);

    }
     for(int i = 0; i <arr.length;i++) {

         arr[i] = stack.pop();    
     }
} 



回答2:


Method top doesn't exist in the Stack of Java. The similar method you're looking for is peek. Take a look at http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

However, you can use only pop, because it returns the removed object.



来源:https://stackoverflow.com/questions/28268945/reversing-an-array-using-a-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!