Showing posts with label Programming (Java). Show all posts
Showing posts with label Programming (Java). Show all posts

Monday, March 13, 2017

Reverse a string using stack in java

In my previous post, I reversed a string in java. I'll do the same thing here using stack.

Steps : 1) Declare an empty stack.
              2) put the string elements in a character array.
              3) Push every single character of the array into the stack.
              4) Pop character one by one from the stack & add the removed character in an empty string.
             

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

public class MyStack {

 
 public static void main(String[] args) {
  
  Scanner scanner = new Scanner(System.in);
  String string = scanner.nextLine();
  String output = "";
    
  Stack stack = new Stack();
  
  char[] array = string.toCharArray();
  
  for (char c : array) {
   stack.push(c);
  }
  
  for (int i = 0; i < array.length; i++){
   char c = (char) stack.pop();
   output += c;
  }
  
  System.out.println("Reversed string : " + output);
  
 }

}


continue reading Reverse a string using stack in java

Reverse a string in java

Here in this section I'll put solution of some simple programming problem which. The following one will reverse a string.

import java.util.Scanner;

public class MyStack {

 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Scanner scanner = new Scanner(System.in);
  String string = scanner.nextLine();
  String output = "";
  StringBuilder stringBuilder = new StringBuilder();
  
  output = stringBuilder.append(string).reverse().toString();
  System.out.println(output);  
  
 }

}


continue reading Reverse a string in java