Google Add

Search

Java Program to Reverse a String using Stack

Write a java program to reverse a string using stack. Given an input string, we have to write a java code to reverse a string using stack data structure.

Before solving this problem, let's understand what is stack?

Stack

A stack is a linear data structure in which insert and delete operations are allowed only at one end. It is also known as LIFO (Last In First Out). In stack, insert operation is called as push and delete operation is called as pop.

Important points about stack -

i) It is an ordered list of similar data type.

ii) It follow LIFO principle (Last in First out).

iii) In stack, push() function is used to insert new elements into the Stack and pop() is used to delete an element from the stack.

iv) Stack is said to be in Overflow state when no memory is available for new element and is said to be in Underflow when it is empty and try to pop an element from stack.

Stack program in c using array


Java Program to Reverse a String using Stack


we have understood the concept of stack, let's write a java code to reverse a string using stack.

import java.util.Scanner;
import java.util.Stack;

public class ReverseStringUsingStack {

     public static void main(String[] args) {
        
        Scanner in = new Scanner(System.in);
       
        System.out.println("Enter a string to reverse");

        //Input string
        String str = in.nextLine();
  
       //Stack declaration
       Stack<Character> stack = new Stack<>();
  
       //Traverse and push each character in stack
       for(int i = 0; i < str.length(); i++) {
          stack.push(str.charAt(i));
       }
  
       //Pop character, which reverse a string
       while(!stack.empty()) {
         System.out.println(stack.pop());
       }

    }

}





MCQ on stack and queue

C program to reverse a string using stack


No comments:

Post a Comment