Java implementation of the queue class

Source: Internet
Author: User

Java implementation of the queue class

ImportJava.util.Iterator;Importjava.util.NoSuchElementException;ImportJava.util.Scanner; Public classQueue<item>ImplementsIterable<item> {    Private intN; PrivateNode<item>First ; PrivateNode<item>Last ; Private Static classNode<item> {        Privateitem Item; PrivateNode<item>Next; }     PublicQueue () { First=NULL; Last=NULL; N= 0; }     Public BooleanIsEmpty () {returnFirst = =NULL; }     Public intsize () {returnN; }     PublicItem Peek () {if(IsEmpty ())Throw NewNosuchelementexception ("Queue underflow"); returnFirst.item; }     Public voidEnqueue (item item) {Node<Item> Oldlast =Last ; Last=NewNode<item>(); Last.item=item; Last.next=NULL; if(IsEmpty ()) First =Last ; ElseOldlast.next =Last ; N++; }     PublicItem dequeue () {if(IsEmpty ())Throw NewNosuchelementexception ("Queue underflow"); Item Item=First.item; First=First.next; N--; if(IsEmpty ()) last =NULL; returnitem; }     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) {Queue<String> q =NewQueue<string>(); Scanner in=NewScanner (system.in);  while(In.hasnext ()) {String Item=In.next (); if(!item.equals ("-") ) Q.enqueue (item); Else if(!Q.isempty ())            System.out.println (Q.dequeue ()); System.out.println ("(" + q.size () + "left on queue)"); }    }}

Java implementation of the queue class

Related Article

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.