使用堆栈反转单词 [英] Reversing word with Stack

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

问题描述

我不知道为什么这会给我一个错误.我在 pop 方法中,我想返回存储在位置 top 的值.虽然它说它们是不兼容的类型.我不明白为什么这应该是一个问题,因为我只想在该位置打印出字符.这是一个更大的计划的一部分,只是为了让你知道并将从不同的班级得到这个词.

I am not sure why this is giving me an error. I am in the method pop and i want to return the value stored at the position top. Though it says they are incompatible types. I do not see why it should be a problem as I only want the character to be printed out at the position. This is part of a bigger program just so you know and will be getting the word from a different class.

public class Stack
{
private int maxSize;
private String[] stackArray;
private int top;
/**
 * Constructor for objects of class Stack
 */
    public Stack(int a)
    {
      maxSize = a;
      stackArray = new String [maxSize];
       top = -1;
    }

   public void push(String j)
   {
     top++;
     stackArray[top] = j;
   }  

   public char pop()
   {
     return stackArray[top--];//Error is here
   }

}

推荐答案

stackArray 是一个 string 数组,你的方法的返回类型是 char.

stackArray is a string array and the return type of your method is char.

用堆栈反转单词

如果您想用 Stack 对象反转单词,请考虑使用 char 数组而不是 String 数组.

If you want to reverse a word with your Stack object, consider using a char array and not a String array.

class Stack
{
private int maxSize;
private char[] stackArray;
private int top;
/**
 * Constructor for objects of class Stack
 */
    public Stack(int a)
    {
      maxSize = a;
      stackArray = new char [maxSize];
       top = -1;
    }

   public void push(char j)
   {
     top++;
     stackArray[top] = j;
   }  

   public char pop()
   {
     return stackArray[top--];
   }

   public int getSize(){
     return maxSize;
   }
}

以及以下测试用例:

        String s = "test";
        Stack st = new Stack(s.length());
        
        for(char c : s.toCharArray())
            st.push(c);
        
        for(int i = 0; i <st.getSize();i++)
            System.out.print(st.pop());

输出:

tset

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

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