Home Tutorial Java Core Reverse String using Stack

 
 

Share on Google+Share on Google+
Reverse String using Stack
Posted on: May 14, 2010 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Reverse String using Stack:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 14, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com