1. Questions
2. Code implementation
/** * Use circular link list to solve Joseph ring problem **///Linked list NodesfunctionNode (Element) { This. Element =element; This. Next =NULL;}//Defining list Classesfunctionllist () { This. Head =NewNode ("Head"); This. Head.next = This. Head; This. Find =find; This. Insert =Insert; This. findprevious =findprevious; This. remove =remove; This. CurrentNode = This. Head; //Move n nodes forward from the current node of the linked list This. Advance =Advance; //How many elements are in the current list This. Count =count; This. display =display;}//Find NodesfunctionFind (item) {varCurrnode = This. Head; while(Currnode.element! =Item) {Currnode=Currnode.next; } returnCurrnode;}//Insert new nodefunctionInsert (newelement, item) {varNewNode =NewNode (newelement); varCurrent = This. Find (item); Newnode.next=Current.next; Current.next=NewNode;}//finds the previous node of the current nodefunctionfindprevious (item) {varCurrnode = This. Head; while(! (Currnode.next = =NULL) && (currNode.next.element! =item)) {Currnode=Currnode.next; } returnCurrnode;}//Remove Current nodefunctionRemove (item) {varPrevNode = This. findprevious (item); if(! (Prevnode.next = =NULL) ) {Prevnode.next=PrevNode.next.next; }}//Move N Nodes forwardfunctionadvance (n) { while(n>0){ if( This. currentNode.next.element = = "Head"){ This. CurrentNode = This. CurrentNode.next.next; }Else{ This. CurrentNode = This. Currentnode.next; } N--; }}//How many elements are in the current listfunctioncount () {varnode = This. Head; vari = 0; while(! (Node.next.element = = "Head") ) {node=Node.next; I++; } returni;}//Output all nodesfunctiondisplay () {varCurrnode = This. Head; while(! (Currnode.next = =NULL) &&! (CurrNode.next.element = = "Head") {document.write (currNode.next.element+ " "); Currnode=Currnode.next; }}varperson =Newllist ();p Erson.insert (' 1 ', ' head ');p Erson.insert (' 2 ', ' 1 ');p Erson.insert (' 3 ', ' 2 ');p Erson.insert (' 4 ', ' 3 ');p Erson.insert (' 5 ', ' 4 ');p Erson.insert (' 6 ', ' 5 ');p Erson.insert (' 7 ', ' 6 ');p Erson.insert (' 8 ', ' 7 ');p Erson.insert (' 9 ', ' 8 ');p Erson.insert (' 10 ', ' 9 ');p erson.display ();d Ocument.write (' <br> ');varn = 3; while(Person.count () > 2) {person.advance (n); Person.remove (person.currentNode.element); Person.display (); document.write (' <br> ');}
The result of the final output is as follows:
Using circular list to implement Joseph ring problem in JavaScript