使用pop和push反转字符串

时间:2013-11-28 17:29:29

标签: java

Stack类可能是个问题。我的堆栈类如下所示。

public class Stack
{
    public static int maxSize; // size of stack array 
    public static char[] stackArray; 
    public static int top; // top of stack 


    /**
     * Constructor for objects of class Stack
     */
    public Stack(String str)
    {
        maxSize = 10; // set array size 
        stackArray = new char[maxSize]; // create array 
        top = -1; // no items yet

    }

    /**
     * An example of a method - replace this comment with your own
     * 
     * @param  y   a sample parameter for a method
     * @return     the sum of x and y 
     */
    public static void push(char j)
    {
        top++;
        stackArray[top] = j; // increment top, insert item 
    }

    public static char pop()
    {
       return stackArray[top--]; //access item, decrement top
    }

    public static boolean isEmpty()
    {
        return (top == -1); 
    }
}

我的主要方法也如下所示。

public static void main()
   {

        Scanner scanner = new Scanner(System.in);
        String str = "";
        Stack stack = new Stack(str);

        System.out.println("Enter a string to be reversed: ");

        str = scanner.nextLine();

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

            stack.push(str.charAt(i));
        }

        String strrev = "";
        while(!stack.isEmpty()){

            strrev += stack.pop(); 
        }

        System.out.println("Reverse of the string \"" + str + "\" is: \"" + strrev + "\"");
    }



       }

问题在于,每次运行程序时都不会输出hello的反向,而是输出数字111108108101104.我认为pop()方法是错误的

2 个答案:

答案 0 :(得分:1)

如下更改pop会解决您的问题。你应该返回一个char而不是long。

public static char pop()
{
   return stackArray[top--]; //access item, decrement top
}

答案 1 :(得分:0)

您已存储了char,然后将其转换为long。试试strrev += Character.toChars(stack.pop());

或者,更好地修改pop方法,返回char。

public static char pop()
{
   return stackArray[top--]; //access item, decrement top
}

对于字符串反转,您可以使用:

new StringBuilder("Hello").reverse().toString()

使用类似Commons.Lang的smth来获得更一般的解决方案。

StringUtils.reverse()
ArrayUtils.reverse(char[] array)

使用内置或库方法更好。与手写相比,它们经常经过充分测试,并且不那么多。