Monday, February 9, 2015

Linked Stack Of Strings.java




LinkedStackOfStrings.java

public class LinkedStackOfStrings
{
    private int N;         
    private Node first;    

    private class Node
   {
        private String item;
        private Node next;
    }
                public boolean isEmpty()
    {
        return first == null;
    }
                 public int size()
                {
                      return N;
                }
              public void push(String item)
               {
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
        N++;
    }

        public String pop()
       {
        if (isEmpty()) throw new RuntimeException("Stack underflow");
        String item = first.item;     
        first = first.next;           
        N--;
        return item;                  
        }
    public static void main(String[] args)
    {
        int max = Integer.parseInt(args[0]);
        LinkedStackOfStrings s = new LinkedStackOfStrings();
        while (!StdIn.isEmpty())
       {
            String item = StdIn.readString();
            if (!item.equals("-"))
         s.push(item);
            else if (s.isEmpty()) 
        StdOut.println("BAD INPUT");
            else                  
        StdOut.print(s.pop());
        }
    }
            }

No comments:

Post a Comment