使用堆栈反转数组 [英] Reversing an array using a stack

查看:49
本文介绍了使用堆栈反转数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用堆栈来反转数组。但是,我在 arr [i] = stack.top(); 上遇到错误,建议在Eclipse中解决该问题是将其更改为 arr [i] = stack.pop(); 或添加演员表。

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

这篇关于使用堆栈反转数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆