简体   繁体   中英

Reversing an array using a stack

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;
} 

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();    
     }
} 

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.

Reverse int array using stack

static int[] reverseArray(int[] arr) {
Stack < String > stack = new Stack();
int len = arr.length;
String[] strArr = new String[len];


for (int i = 0; i < arr.length; i++) {
    strArr[i] = String.valueOf(arr[i]);
    stack.push(strArr[i]);
}
for (int i = 0; i < strArr.length; i++) {
    strArr[i] = stack.pop();
    arr[i] = Integer.parseInt(strArr[i]);
}
return arr;

}

import java.util.Arrays;
import java.util.Stack;

public class reverse {
    public static void main(String[]args){
        Integer arr[] = {3,5,6,8};
        Stack<Integer> st = new Stack<>();
        for(int i =0;i<arr.length;i++){
            st.push(arr[i]);
        }
        for(int i =0;i<arr.length;i++){
            arr[i]=st.peek();
            st.pop();
        }
        System.out.println(Arrays.toString(arr));

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM