A Stack of Strings by array - Java Data Structure

Java examples for Data Structure:Stack

Description

A Stack of Strings by array

Demo Code

import static java.lang.System.out;


public class FixedCapacityStackOfStrings {

    private String[] data;
    private int N;

    public FixedCapacityStackOfStrings(int capacity) {
        data = new String[capacity];
    }//ww w.  ja  v a 2 s  .c  om

    public boolean isEmpty() {
        return N == 0;
    }
  
    public void push(String item) {
        data[N++] = item;
    }
    
    public String pop() {
        String item = data[--N];
        data[N] = null;
        return item;
    }
    
    public static void main(String[] args) {
      FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(10);
      stack.push("1");
      stack.push("2");
      stack.push("3");
      stack.push("4");
      stack.push("5");
      stack.push("6");
      stack.push("7");
      stack.push("A");
      stack.push("C");
      stack.push("K");
        
        while (!stack.isEmpty()) {
            out.printf("%s ",stack.pop());
        }
    }
}

Related Tutorials