Monday, February 9, 2015

ArrayStackOfStrings.java



ArrayStackOfStrings.java

import java.util.Iterator;

public class ArrayStackOfStrings implements Iterable
{
    private String[] a; 
    private int N;      

    public ArrayStackOfStrings(int max)
   { 
           a = new String[max];   
    }
    public boolean isEmpty()           
   { 
         return (N == 0);          
   }
    public void push(String item)      
    { 
         a[N++] = item;          
     }
    public String pop()               
    {   
        return a[--N];        
     }
    public Iterator iterator()
 {  
       return new ArrayIterator();
  }
             public class ArrayIterator implements Iterator
              {
        private int i = N-1;
                    public boolean hasNext()
                     {
                              return i >= 0;
                      }
        public String next()   
        {
                 return a[i--];
         }
        public void remove()     
       { throw new UnsupportedOperationException(); }
    }
                public static void main(String[] args)
                    {
        int max = Integer.parseInt(args[0]);
        ArrayStackOfStrings stack = new ArrayStackOfStrings(max);
        while (!StdIn.isEmpty())
         {
            String item = StdIn.readString();
            if (!item.equals("-"))
            stack.push(item);
            else if (stack.isEmpty()) 
            StdOut.println("BAD INPUT");
            else                      
            StdOut.print(stack.pop() + " ");
        }
        StdOut.println();
                    StdOut.print("Left on stack: ");
        for (String s : stack)
        {
            StdOut.print(s + " ");
        }
        StdOut.println();
    }
}

No comments:

Post a Comment