问题描述:

How do I write a method that when passed an array of integers, returns the array reversed, using a stack?

I am a total noob at Java please don't ask me for my own attempt as I don't know where to start. Any help would be greatly appreciated.

网友答案:
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < array.length; i++) {
    stack.push(array[i]);
}
for (int i = 0; i < array.length; i++) {
    array[i] = stack.pop();
}
网友答案:

Considering you as a beginner in Java and Data Structure.
Stack is a data structure which works on LIFO(Last In First Out) principle. You can imagine Stack as a container of CD(Compact Disks). You put some CDs there, then when you are about to fetch them you get the CD first which you've put last.
In your case, you just have to read those items from the given array and put them in the Stack one by one. Then simply fetch them one by one from the Stack and put in a new array. You'll get the reversed array.
Use push(Integer item) and pop() of java.util.Stack class for putting into and fetching the top most item from the Stack.

网友答案:

Because a stack is "last in, first out", when you pop a value off the stack and insert it into a new array it will end up in reverse order.

int[] arr = {1, 2, 3, 4, 5};

Poping values off arr and adding them to a new array will result in:

reverse = {5, 4, 3, 2, 1};

Pop the values off arr using a for loop:

int[] reverse = new int[arr.length];

for(int i = 0; i < arr.length; i++){
    reverse[i] = pop();
}
return reverse;
相关阅读:
Top