Create stack to reverse a string in Java

Description

The following code shows how to create stack to reverse a string.

Example


//ww w  .ja  v  a  2s. c o m
class Stack {
  private int maxSize;

  private char[] stackArray;

  private int top;

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

  public void push(char j) {
    stackArray[++top] = j;
  }

  public char pop() {
    return stackArray[top--];
  }

  public char peek() {
    return stackArray[top];
  }

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

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

public class Main {
  public static void main(String[] args) {
    String input = "java2s.com";
    int stackSize = input.length();

    Stack theStack = new Stack(stackSize);

    for (int j = 0; j < input.length(); j++) {
      char ch = input.charAt(j);
      theStack.push(ch);
    }

    while (!theStack.isEmpty()) {
      char ch = theStack.pop();
      System.out.println(ch);
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Collection »




Java ArrayList
Java Collection
Java Comparable
Java Comparator
Java HashMap
Java HashSet
Java Iterator
Java LinkedHashMap
Java LinkedHashSet
Java LinkedList
Java List
Java ListIterator
Java Map
Queue
Java Set
Stack
Java TreeMap
TreeSet