Posts which you will also like.

Sunday, September 5, 2010

Reversing the String using Stack

import javax.swing.JOptionPane;
class stack
{
    private int top;
    private char[] stack;
    public stack(int cap)
    {   
        stack=new char[cap];
        top=-1;
    }
    public void push(char element)
    {
        stack[++top]=element;
    }
    public char pop()
    {
        return stack[top--];
    }
    public boolean isEmpty()
    {
        return top<0;
    }
    public boolean isFull()
    {
        return top==stack.length-1;
    }
   
}
class use
{
    public static void main(String []args)
    {    String revs="";
        String s=JOptionPane.showInputDialog(null,"Enter a string:");
        int len=s.length();
        stack st=new stack(len);
        for(int i=0;i
        {
            st.push(s.charAt(i));
        }
        while(!st.isEmpty())
        {
            revs+=st.pop();
        }
        JOptionPane.showMessageDialog(null,"Original String is:"+s+"\n Reversed string is:"+revs);
       
    }
}
OUTPUT:

Enter a string:Rajeev
Original String is:Rajeev
 Reversed string is:veejaR

No comments:

Post a Comment

Your comment may wait for moderation....

DMCA.com Protected by Copyscape Online Plagiarism Tool