Using stack to reverse a string : Your Stack « Collections « Java Tutorial






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 MainClass {
  public static void main(String[] args) {
    String input = "input";
    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);
    }
  }
}
t
u
p
n
i








9.52.Your Stack
9.52.1.A stack allows access to only one data item: the last item inserted
9.52.2.Using stack to reverse a string
9.52.3.Stack Example: Delimiter Matching
9.52.4.Demonstrating a stack implemented as a list