Using Stack To reverse Input String
/*
* To change this license header, choose License Headers in Project *Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package stackimplementation;
import java.util.Scanner;
/*
@author Adeniran Adetunji
*/
/*
This program uses stack implementation to reverse a string e.g. Input "CAT" will output "TAC"
*/
public class StackImplementation {
/* Declare class variables Top: which keeps track the top of the stack, Size: the size of the stack that is predetermined, stack implementationwithan array "myStack".
*/
int size;
char [] myStack;
int top;
//set stack size to accomodate the string input
void setSize(String n)
{
int stackSize = n.length();
size = stackSize;
myStack = new char [size];
top = myStack.length;
}
//push string character-by-character into stack
void push(String myWord)
{
if (top<=0)
{
System.out.println("Stack is full");
}
else
{
for (int i = 0; i<myWord.length(); i++)
{
myStack[top-1]=myWord.charAt(i);
top--; //update top
}
}
}
//POP string in Last-in-first-out order from stack
String pop()
{
String outString="";
if (top==myStack.length)
{
System.out.println("Stack is Empty, Enter String to reverse");
}
for (int i= 0; i<myStack.length; i++)
{
outString = outString+myStack[i];
top++;
}
return outString;
}
//reverse string using push and pop methods
String reverse(String n)
{
setSize(n);
push(n);
n = pop();
return n;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String str; //Declaratio of string to be reversed
Scanner read = new Scanner(System.in);
System.out.println("Enter String Input: ");
str = read.nextLine(); //read string from keyboard input
//Declare a new stackImplementaton object
StackImplementation reverseString = new StackImplementation();
//reverse string input using stackImplementation
str = reverseString.reverse(str);
//Prints input string in reverse order
System.out.println(str);
}
}
OUTPUT:
run:
Enter String Input:
Tunji
ijnuT
BUILD SUCCESSFUL (total time: 3 seconds)
No comments:
Post a Comment
Please drop your comment here, thanks.