karol_dziachan

JOSEPHUS_PROBLEM

Mar 19th, 2020
583
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.51 KB | None | 0 0
  1. public class GFG {
  2.  
  3.     // Node class to store data  
  4.     static class Node
  5.     {
  6.         public int data ;
  7.         public Node next;
  8.         public Node( int data )
  9.         {
  10.             this.data = data;
  11.         }
  12.     }
  13.  
  14.     /* Function to find the only person left
  15.     after one in every m-th node is killed
  16.     in a circle of n nodes */
  17.     static void getJosephusPosition(int m, int n)
  18.     {
  19.         // Create a circular linked list of
  20.         // size N.
  21.         Node head = new Node(1);
  22.         Node prev = head;
  23.         for(int i = 2; i <= n; i++)
  24.         {
  25.             prev.next = new Node(i);
  26.             prev = prev.next;
  27.         }
  28.  
  29.         // Connect last node to first
  30.         prev.next = head;
  31.          
  32.         /* while only one node is left in the
  33.         linked list*/
  34.         Node ptr1 = head, ptr2 = head;
  35.  
  36.         while(ptr1.next != ptr1)
  37.         {
  38.  
  39.             // Find m-th node
  40.             int count = 1;
  41.             while(count != m)
  42.             {
  43.                 ptr2 = ptr1;
  44.                 ptr1 = ptr1.next;
  45.                 count++;
  46.             }
  47.  
  48.             /* Remove the m-th node */
  49.             ptr2.next = ptr1.next;
  50.             ptr1 = ptr2.next;
  51.         }
  52.         System.out.println ("Last person left standing " +
  53.                 "(Josephus Position) is " + ptr1.data);
  54.     }
  55.  
  56.     /* Driver program to test above functions */
  57.     public static void main(String args[])
  58.     {
  59.         int n = 14, m = 2;
  60.         getJosephusPosition(m, n);
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment