Coders Packet

REVERSING OF A STRING USING STACK IN JAVA PROGRAMMING

By BODA KAVYA SREE

In this tutorial, we are going to learn how to build a java code to reverse a string using stacks. Here, in this case, we have used stack operations like push and pop to reverse a string.

Implementation of the below Java Code :

Here, in this java code, we can easily reverse a string using the stacks. Once the input is given it gives the output of the respective string in the reverse format.

In this implementation of java code first, we need to create an empty stack. One by one push all characters of a string to an empty stack. To push characters into a stack we create a function called a push. Now, one by one pop all characters from stack and put them back to a string. We create a function called pop to pop(delete) the characters of string. Now we got the respective string. We will print the string in the output which is reversed.

As we know we have some operations in the stack. We have used push, pop operations in this java code to reverse a string and we can have fun too...

import java.util.*;
class Stack
{
    int size;
    int top;
    char[] a;
    boolean isEmpty()
    {
        return (top < 0);
    }
     
    Stack(int n)
    {
        top = -1;
        size = n;
        a = new char[size];
    }
    boolean push(char x)
    {
        if (top >= size)
        {
        System.out.println("Stack Overflow");
        return false;
        }
        else
        {
            a[++top] = x;
            return true;
        }
    }
    char pop()
    {
        if (top < 0)
        {
        System.out.println("Stack Underflow");
        return 0;
        }
        else
        {
            char x = a[top--];
            return x;
        }
    }
}
class Main
{
    public static void reverseString(StringBuffer strg)
    {
        int n = strg.length();
        Stack obj = new Stack(n);
        int i;
        for (i = 0; i < n; i++)
        obj.push(strg.charAt(i));
        for (i = 0; i < n; i++)
        {
            char ch = obj.pop();
            strg.setCharAt(i,ch);
        }
    }
    public static void main(String[] args)
    {
        System.out.println("Enter a string to be reversed :");
        Scanner scan = new Scanner(System.in);
        String r = scan.nextLine();
        StringBuffer s= new StringBuffer(r);
        reverseString(s);
        System.out.println();
        System.out.println("The reversed string is " + s);
    }
}

OUTPUT 1:

OUTPUT 2:

Download project

Reviews Report

Submitted by BODA KAVYA SREE (Kavyasree1903)

Download packets of source code on Coders Packet