简体   繁体   中英

Using stacks to reverse string?

This is my code so far, I need to create a reverse string so input= "hello" will output = "olleh"... The errors I'm having is in push and pop part of the code. I can't use StringBuffer. The error is -

Exception in thread "main" java.lang.Error: Unresolved compilation problems: l cannot be resolved l cannot be resolved

at E.reverse(E.java:10) at E.main(E.java:17)

Can you please help?

public class Rev {

    public static String reverse(String s) {

        MyStack st = new MyStack();
        while (!s.isEmpty()) {
            String k = st.toString();
            st.push(s);
        }
        while (!s.isEmpty()) {
            String p = st.pop();
            return s;
        }}
        public static void main(String[] args) {
            System.out.println(reverse("hello"));
    }
}

A simple way is:

 private Stack s = new Stack();

    public void reversestack( String str )
    {
        for(int j = 0; j < str.length(); j++)
        {
            s.push( str.charAt( j ) );
        }

        while(s.isEmpty() != true)
        {    
            System.out.println(s.pop());
        }

    }

How about trying like this:-

public class StringReverse {

    public static void main(String [] args){

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

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

        str = scanner.nextLine();

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

            stack.push(str.substring(i,i+1));
        }

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

            strrev += stack.pop(); 
        }

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

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