Stack - Reversing a String


The concept for reversing a string using a stack is to remember that the last item to be inserted will always be the first item to be removed (LIFO). In this sample, we created our own stack class with its own built in stack operations, which includes other operations to distinguish the status of the stack(isEmpty(), and isFull()). the actual code for reversing is the doRev() function which is then utilized within the main() function.

The code:

import java.io.*;

public class Stack //the stack class to create a stack. by MGDT
{
char arr[]; //the Stack attribute represented by a character array
int top=-1; //the Stack attribute to determine the top of the stack
public Stack(int size) //the Stack constructor to initialize the size of the stack
{
arr=new char[size];
}
public void push(char ch) //the Stack behavior for pushing to the stack
{
if(!isFull())
arr[++top] = ch;
else
System.out.println("Stack is already full.");
}
public char pop() //the Stack behavior for popping from the stack
{
if(!isEmpty())
return arr[top--];
else
{
System.out.println("Stack is already empty.");
return ' ';
}
}
public char peek() //the Stack behavior to retrieve data from a stack
{
if(!isEmpty())
return arr[top];
else
{
System.out.println("Stack is empty.");
return ' ';
}
}
public boolean isEmpty() //the Stack behavior to determine if stack is empty
{
if(top==-1) return true;
else return false;
}
public boolean isFull() //the Stack behavior to determine if stack is full
{
if(top==arr.length-1) return true;
else return false;
}
public static void main(String args[])throws IOException //Main method
{
BufferedReader inp=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Type string to reverse: ");
String str=inp.readLine();
System.out.println("The entered string in reverse: " + doRev(str));
}
public static String doRev(String input) //static method for reversing a string
{
int stackSize = input.length();
Stack theStack = new Stack(stackSize);
for(int i=0; i
{
char c=input.charAt(i);
theStack.push(c);
}
String output="";
while(!theStack.isEmpty())
{
char c=theStack.pop();
output = output + c;
}
return output;
}
}

0 comments:

Post a Comment