Skip to content

Instantly share code, notes, and snippets.

@Juliet-Selebalo
Created June 22, 2018 18:03
Show Gist options
  • Save Juliet-Selebalo/79eb0351f80d19ec48f0ba3a74b0fd96 to your computer and use it in GitHub Desktop.
Save Juliet-Selebalo/79eb0351f80d19ec48f0ba3a74b0fd96 to your computer and use it in GitHub Desktop.
Creaing a queue interface and implementing it using an array
import java.util.Arrays;
import queue.QueueInterface;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Student
* @param <T>
*/
public class Queue <T> implements QueueInterface <T> {
int head;
int tail;
int size;
T[] queue;
int capacity;
boolean full;
//int last;
public Queue(int capacity){
queue = (T[]) new Object[capacity];
this.size = 0;
this.head = 0;
this.tail = -1;
this.capacity = capacity;
}
@Override
public void enqueue(T t) {
this.tail++;
if (tail == capacity && head!=0){
this.tail = (tail)%capacity;
}
if(!isFull()){
queue[tail] = t;
}
else{
expand();
enqueue(t);
}
this.size++;
}
@Override
public T dequeue() {
if(head!=capacity-1){
this.head = head++;
this.size = size--;
}
else{
this.head = 0;
}
return queue[head];
}
@Override
public T getFront() {
return this.queue[head];
}
public boolean isFull(){
if(capacity == size){
full = true;
}
return full;
}
public void expand(){
this.capacity = capacity*2;
this.queue = Arrays.copyOf(queue, capacity);
}
/**
*
* @return
*/
@Override
public int getLength(){
return this.size;
}
}
package queue;
/**
*
* @author Student
* @param <T>
*/
public interface QueueInterface <T> {
/**
*
* @param t
*/
void enqueue(T t);
T dequeue(); //removes the first element
int getLength(); //gets the number of elements in the queue
T getFront(); //just reads the value without removing it from queue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment