Josephus Ring class problem, Java implementation

Source: Internet
Author: User

Write a two-way loop linked list, get a counter, I define the time to three, automatically delete the current node, very simple.

  

 PackageCom;ImportJava.util.Scanner;/** Joseph Ring problem, there is a circle of n individuals, counting to 3 of that person to dequeue, the next person continues from the beginning*/ Public classJosephus { Public Static voidMain (string[] args) {Scanner s=NewScanner (system.in); intn =Integer.parseint (S.nextline ()); Node First=NewJosephus (). Startrun (n); intCount = 1;  while(First.next! =First ) { First=First.next; Count++; if(Count = = 3) {First.previous.next=First.next; First.next.previous=first.previous; First=First.next; Count= 1; }} System.out.println ("The last number left is:" +FIRST.N); }         PublicNode Startrun (intN) {Node First=NewNode (); First.previous=NULL; FIRST.N= N;//This gives the list value, flashbacksNode current =First ; Node Last=First ;  while((--n) >0) {Current.next=NewNode (); Current=Current.next; CURRENT.N=N; Current.previous=Last ; Last=Current ; } Current.next=First ; First.previous=Current ; returnFirst ; }    classNode {intN;        Node Next;    Node previous; }}

Josephus Ring class problem, Java implementation

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.