Advertisement
jtentor

DemoQueue3 - SpecialQueue.java

May 17th, 2020
516
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class SpecialQueue<ELEMENT> {
  2.     private ELEMENT[] data;
  3.     private int head;
  4.     private int tail;
  5.     private int count;
  6.  
  7.     public SpecialQueue() {
  8.         this(10);
  9.     }
  10.  
  11.     public SpecialQueue(int capacity) {
  12.         this.data = (ELEMENT[]) new Object[capacity];
  13.         this.head = 0;
  14.         this.tail = 0;
  15.         this.count = 0;
  16.     }
  17.  
  18.     // Equivalent to Count property in C#
  19.     public int size() {
  20.         return this.count;
  21.     }
  22.  
  23.     private int Next(int position) {
  24.         return (++position >= this.data.length)? 0: position;
  25.     }
  26.  
  27.     // Equivalent to Enqueue method in C#
  28.     public void add(ELEMENT element) {
  29.         if (this.count >= this.data.length) {
  30.             throw new RuntimeException("La cola está llena...");
  31.         }
  32.         this.data[this.tail] = element;
  33.         this.tail = this.Next(this.tail);
  34.         ++this.count;
  35.     }
  36.  
  37.     // Equivalent to Dequeue method in C#
  38.     public ELEMENT remove() {
  39.         if (this.count <= 0) {
  40.             throw new RuntimeException("La cola está vacía...");
  41.         }
  42.         ELEMENT temp = this.data[this.head];
  43.         this.head = this.Next(this.head);
  44.         --this.count;
  45.         return temp;
  46.     }
  47.  
  48.     public ELEMENT[] toArray() {
  49.         ELEMENT[] result =  (ELEMENT[]) new Object[this.size()];;
  50.         for (int pos = this.head, c = 0; c < this.count; c++) {
  51.             result[c] = this.data[pos];
  52.             pos = this.Next(pos);
  53.         }
  54.         return result;
  55.     }
  56.  
  57.     public SpecialQueue<ELEMENT> join(SpecialQueue<ELEMENT> other) {
  58.         SpecialQueue<ELEMENT> result =
  59.         new SpecialQueue<ELEMENT>((this.size() + other.size()) * 2);
  60.  
  61.         ELEMENT[] data = this.toArray();
  62.         for (ELEMENT e : data) {
  63.             result.add(e);
  64.         }
  65.  
  66.         data = other.toArray();
  67.         for (ELEMENT e : data) {
  68.             result.add(e);
  69.         }
  70.  
  71.         return result;
  72.     }
  73. }
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement