Java implementation Stack Class

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.