Reverse String using Stack


 

Reverse String using Stack

In this section, you will learn how to reverse the string using these operations.

In this section, you will learn how to reverse the string using these operations.

Reverse String using Stack

You all are aware of Stack, a data structure, having two fundamental operations: push and pop. In stacks, items are removed in the reverse order from that in which they are added. The push operation is responsible for adding the element and pop for removing. Here we are going to reverse the string using these operations.

Here is the code:

import java.util.*;

class StackReverseString {
	public static String revString(String str) {
		Stack stack = new Stack();
		for (int i = 0; i < str.length(); i++) {
			stack.push(str.substring(i, i + 1));
		}
		String strrev = "";
		while (!stack.isEmpty()) {
			strrev += stack.pop();
		}
		return strrev;
	}

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter a string: ");
		String str = scanner.nextLine();
		String reversedString = StackReverseString.revString(str);
		System.out.println(reversedString);
	}
}

Output:

Enter a String:
Hello World
dlroW olleH

Ads