Monday, February 9, 2015

Stack.java in pgm



Stack.java

import java.util.Iterator;
import java.util.NoSuchElementException;
             public class Stack implements Iterable
 {
    private int N;         
    private Node first;    

   private class Node
 {
        private Item item;
        private Node next;
    }
                 public Stack()
{
        first = null;
        N = 0;
    }

    public boolean isEmpty()
   {
        return first == null;
    }

 public int size()
{
        return N;
    }
    public void push(Item item)
{
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
        N++;
    }

    public Item pop()
   {
        if (isEmpty()) throw new RuntimeException("Stack underflow");
        Item item = first.item;       
        first = first.next;           
        N--;
        return item;                  
    }
             public Item peek()
{
        if (isEmpty()) throw new RuntimeException("Stack underflow");
        return first.item;
    }

  
    public String toString()
   {
        StringBuilder s = new StringBuilder();
        for (Item item : this)
            s.append(item + " ");
        return s.toString();
    }
      

         public Iterator iterator() 
{
 return new ListIterator(); 
}
             private class ListIterator implements Iterator
 {
        private Node current = first;
        public boolean hasNext() 
{
 return current != null;                  
  }
        public void remove()     
{
throw new UnsupportedOperationException();
 }
            public Item next()
      {
            if (!hasNext()) throw new NoSuchElementException();
            Item item = current.item;
            current = current.next;
            return item;
        }
    }
             public static void main(String[] args)
   {
        Stack s = new Stack();
        while (!StdIn.isEmpty())
      {
            String item = StdIn.readString();
            if (!item.equals("-")) s.push(item);
            else if (!s.isEmpty()) StdOut.print(s.pop() + " ");
        }
        StdOut.println("(" + s.size() + " left on stack)");
    }
}

No comments:

Post a Comment