Stack and Reverse a String Algorithm

The Stack data structure allows for LIFO (last in – first out) functionality. We can use is it within complex structures where we need the order of items to be reversed.
One of a simple examples would be a string reverse method:

public static void main(String[] args) {		
  String str = "system";
  String result = App.reverseString(str);
  System.out.println(result);
}
	
// Algorithm to reverse the string that is passed in as a parameter
public static String reverseString(String str) {  
  Stack stack = new Stack(str.length());
  for (int i = 0; i < str.length(); i++) {			
    stack.push(str.charAt(i));
  }
  String result = "";
  while (!stack.isEmpty()) {
    result  += stack.pop();		
  }
  return result;
}

The Stack class may look like this:

public class Stack {

	// Store the size of the stack
	private int maxSize;

	// Store list of items
	private char[] stackArray;

	// Index position of the last item on the top of the stack
	private int top;

	public Stack(int size) {
		this.maxSize = size;
		this.stackArray = new char[maxSize];
		this.top = -1;
	}

	public void push(char j) {
		if (isFull()) {
			System.out.println(" this stack is already full");
		} else {
			top++;
			stackArray[top] = j;
		}
	}

	public char pop() {
		if (isEmpty()) {
			System.out.println(" this stack is already empty");
			return 0;
		} else {
			int old_top = top;
			top--;
			return stackArray[old_top];	
		}		
	}

	public long peak() {
		return stackArray[top];
	}

	public boolean isEmpty() {
		return (top == -1);
	}

	public boolean isFull() {
		return (maxSize - 1 == top);
	}
}

Of course, there would be a much simpler solution for such a basic operation as a string reverse, but the code above just illustrates the LIFO benefit.

public static String reverseString(String str) {        
    String result = "";   
    for (int i = str.length() - 1; i >= 0; i--) {
      result += str.charAt(i);        
    }        
return result;    
}