Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Viimeinen {
  4.  
  5.     public static Scanner lukija = new Scanner(System.in);
  6.  
  7.     public static void main(String[] args) {
  8.         System.out.print("Kuinka monta? ");
  9.         int n = lukija.nextInt();
  10.         int voittaja = viimeinen(n);
  11.         System.out.println("Voittaja: " + voittaja);
  12.  
  13.     }
  14.  
  15.     public static int viimeinen(int n) {
  16.         Rinki rinki = new Rinki();
  17.  
  18.         for (int i = 1; i <= n; i++) {
  19.             rinki.insert(i);
  20.         }
  21.        
  22.         Rinkisolmu aloitus = rinki.getAlku();
  23.  
  24.         while(rinki.getKoko() > 1) {
  25.             aloitus = rinki.delete(aloitus);
  26.         }
  27.  
  28.         return rinki.getAlku().getKey();
  29.     }
  30. }
  31.  
  32. class Rinki {
  33.  
  34.     Rinkisolmu alku;
  35.     Rinkisolmu loppu;
  36.     int koko;
  37.  
  38.     void insert(int key) {
  39.         Rinkisolmu uusi = new Rinkisolmu(key);
  40.         koko++;
  41.  
  42.         if (alku == null) {
  43.             alku = uusi;
  44.             loppu = alku;
  45.             alku.next = loppu;
  46.             loppu.next = alku;
  47.             return;
  48.         }
  49.  
  50.         loppu.next = uusi;
  51.         loppu = uusi;
  52.         loppu.next = alku;
  53.     }
  54.  
  55.     Rinkisolmu delete(Rinkisolmu edel) {
  56.         koko--;
  57.  
  58.         if(edel == loppu) {
  59.             alku = alku.next;
  60.             loppu.next = alku;
  61.             return alku;
  62.         }
  63.         if(edel.next == loppu) {
  64.             loppu = edel;
  65.             loppu.next = alku;
  66.             return alku;
  67.         }
  68.         Rinkisolmu pois = edel.next;
  69.         edel.next = pois.next;
  70.         return edel.next;
  71.  
  72.  
  73.     }
  74.  
  75.     int getKoko() {
  76.         return koko;
  77.     }
  78.  
  79.     Rinkisolmu getAlku() {
  80.         return alku;
  81.     }
  82.  
  83. }
  84.  
  85. class Rinkisolmu {
  86.  
  87.     int key;
  88.     Rinkisolmu next;
  89.  
  90.     Rinkisolmu(int k) {
  91.         key = k;
  92.     }
  93.  
  94.     Rinkisolmu getNext() {
  95.         return next;
  96.     }
  97.  
  98.     int getKey() {
  99.         return key;
  100.     }
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement