1. Concept
/*--------------definition and test code for the bidirectional queue class----------------*/functionQueue () { This. DataStore = []; This. Enqueuefront =Enqueuefront; This. Enqueueback =Enqueueback; This. Dequeuefront =Dequeuefront; This. Dequeueback =Dequeueback; This. Front =Front; This. Back =Back ; This. toString =toString; This. Empty =empty;}//The trailing queue is the addition of an element at the end of the arrayfunctionEnqueueback (Element) { This. Datastore.push (Element);}//to join the head is to add an element to the head of the arrayfunctionEnqueuefront (Element) { This. Datastore.splice (0,0, Element);}//The tail out of the queue is the last element of the delete arrayfunctionDequeueback () {return This. Datastore.splice ( This. datastore.length-1, 1);}//The first element of the array is removed from the team.functionDequeuefront () {return This. Datastore.shift ();}//Take out the first element of the arrayfunctionFront () {return This. datastore[0];}//remove the last element of the arrayfunctionBack () {return This. datastore[ This. datastore.length-1];}functiontoString () {varRetstr = ""; for(vari=0; i< This. datastore.length; ++i) {retstr+= This. Datastore[i] + " " } returnretstr;}//determine if the array is emptyfunctionempty () {if( This. Datastore.length = = 0){ return true; }Else{ return false; } }//returns the number of elements in an arrayfunctioncount () {return This. Datastore.length;}varQ =NewQueue (); Q.enqueuefront ("1"); Q.enqueuefront ("2"); Q.enqueueback ("3"); Q.enqueueback ("4");d Ocument.write (q.tostring ());d Ocument.write (' <br> '); Q.dequeuefront ();d ocument.write (q.tostring ());d Ocument.write (' <br> '); Q.dequeueback ();d ocument.write (q.tostring ());d Ocument.write (' <br> ');d Ocument.write (' <br> ');
Output results
2. Code implementation
/*---------------------------Determine if a string is a palindrome-------------------------*/functionIspalindrome (str) {varQueue =NewQueue (); for(vari=0; i<str.length; i++) {Queue.enqueuefront (str[i]); } varNewstr = ""; while(!Queue.empty ()) {Newstr+=Queue.dequeuefront (); } document.write (NEWSTR); document.write (' <br> '); if(str = =newstr) {Document.writeln (str+ "is a palindrome"); }Else{Document.writeln (str+ "Not palindrome"); }}ispalindrome ("Racecar");d Ocument.write (' <br> '); Ispalindrome ("Helloword");
Output Result:
bidirectional queues in JavaScript