Java implementation Stack Class
ImportJava.util.Iterator;Importjava.util.NoSuchElementException;ImportJava.util.Scanner; Public classStack<item>ImplementsIterable<item> { Private intN; PrivateNode<item>First ; Private Static classNode<item> { Privateitem Item; PrivateNode<item>Next; } PublicStack () { First=NULL; N= 0; } Public BooleanIsEmpty () {returnFirst = =NULL; } Public intsize () {returnN; } Public voidpush (item item) {Node<Item> Oldfirst =First ; First=NewNode<item>(); First.item=item; First.next=Oldfirst; N++; } PublicItem Pop () {if(IsEmpty ())Throw NewNosuchelementexception ("Stack underflow"); Item Item=First.item; First=First.next; N--; returnitem; } PublicItem Peek () {if(IsEmpty ())Throw NewNosuchelementexception ("Stack underflow"); returnFirst.item; } PublicString toString () {StringBuilder s=NewStringBuilder (); for(Item Item: This) S.append (item+ " "); returns.tostring (); } PublicIterator<item>iterator () {return NewListiterator<item>(first); } Private classListiterator<item>ImplementsIterator<item> { PrivateNode<item>Current ; PublicListiterator (node<item>First ) { Current=First ; } Public BooleanHasnext () {returnCurrent! =NULL; } Public voidRemove () {Throw Newunsupportedoperationexception ();} PublicItem Next () {if(!hasnext ())Throw Newnosuchelementexception (); Item Item=Current.item; Current=Current.next; returnitem; } } Public Static voidMain (string[] args) {Stack<String> s =NewStack<string>(); Scanner in=NewScanner (system.in); while(In.hasnext ()) {String Item=In.next (); if(!item.equals ("-") ) S.push (item); Else if(!s.isempty ()) System.out.println (S.pop () + ""); System.out.println ("(" + s.size () + "left on stack)"); } }}
Java implementation Stack Class