1 //implementing queues with a double-ended linked list2 /**3 * Node class4 */5 classLINKQ {6 Private Longdata;7 PublicLINKQ Next;8 9 PublicLINKQ (Longd) {Ten This. data =D; One } A - PublicString toString () { - returnString.valueof ( This. data); the } - } - /** - * Double-ended linked list class + */ - classFirstlastlink { + PrivateLINKQ first; A PrivateLINKQ last; at - PublicFirstlastlink () { -First =NULL; -Last =NULL; - } - in Public BooleanIsEmpty () { - returnFirst = =NULL; to } + - Public voidInsertlast (linkq l) { the if(IsEmpty ()) *First =l; $ ElsePanax NotoginsengLast.next =l; -Last =l; the } + A PublicLINKQ Deletefirst () { theLINKQ temp =First ; + if(First.next = =NULL) -Last =NULL; $First =First.next; $ returntemp; - } - the @Override - PublicString toString () {Wuyi if(IsEmpty ()) the return"[]"; -LINKQ Curr =First ; WuStringBuilder SB =NewStringBuilder (); -Sb.append ("["); About while(Curr! =NULL) { $Sb.append (Curr.tostring ()). Append (","); -Curr =Curr.next; - } -Sb.deletecharat (Sb.length ()-1); ASb.append ("]"); + returnsb.tostring (); the } - $ Public voiddisplay () { the System.out.println (toString ()); the } the } the /** - * Queue class in * Like the implementation of the Stack class in the previous example, the emphasis is on conceptual entities, independent of their specific implementations. the * The stack and queue are the same with arrays or linked lists. The importance of the stack is its push pop operations and how they are used; the importance of the queue is removed from the team head, inserted from the end of the team, and how to use it. the * The intrinsic mechanism for implementing these operations is, in fact, unimportant in its importance. About */ the classlinkqueue{ the PrivateFirstlastlink link; the PublicLinkqueue () { +link =NewFirstlastlink (); - } the Public BooleanIsEmpty () {Bayi return This. Link.isempty (); the } the Public voidInsert (linkq l) { - This. Link.insertlast (l); - } the Publiclinkq Remove () { the return This. Link.deletefirst (); the } the PublicString toString () { - return This. link.tostring (); the } the Public voiddisplay () { the System.out.println (toString ());94 } the } the Public classLinkqueuedemo { the Public Static voidMain (string[] args) {98Linkqueue queue =Newlinkqueue (); About for(inti = 0; I < 5; i++) { -LINKQ l=NewLINKQ (i);101 Queue.insert (l);102 Queue.display ();103 }104 while(!Queue.isempty ()) { theSystem.out.print ("remove element:" +Queue.remove ());106System.out.print (". Now queue is:");107 Queue.display ();108 }109 } the}
Java data structure and algorithms note-ch5-List-5 using a double-ended list to implement the queue