Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Queue {
- long[] queueArray;
- int front;
- int rear;
- int maxSize;
- int nItems;
- // Constructors
- public Queue(){
- front = 0;
- rear = -1;
- maxSize = 0;
- nItems = 0;
- queueArray = new long[0];
- }
- public Queue(int maxSize) {
- front = 0;
- rear = -1;
- this.maxSize = maxSize;
- nItems = 0;
- queueArray = new long[maxSize];
- }
- // Methods
- public boolean isEmpty() {
- if(nItems == 0) {
- return true;
- }
- else {
- return false;
- }
- }
- public boolean isFull() {
- return (nItems == maxSize);
- }
- public int size() {
- return nItems;
- }
- public void printQueue() {
- for(int i=front; i<=rear; i++) {
- System.out.print(queueArray[i] + " ");
- }
- System.out.println();
- System.out.println();
- }
- public void insert(long j) {
- if(isFull()) {
- System.out.println("Queue is full! " + j + " cannot be inserted.");
- }
- else {
- //if(rear == maxSize - 1) {
- for(int i=0; i<nItems; i++) {
- // Shift
- queueArray[i] = queueArray[i + front];
- }
- front = 0;
- rear = nItems - 1;
- //}
- rear++;
- queueArray[rear] = j;
- nItems++;
- }
- }
- public long remove() {
- if(isEmpty()) {
- System.out.println("Queue is empty. There are no items to be removed.");
- return -10000;
- }
- long temp = queueArray[front];
- front++;
- nItems--;
- if(front == maxSize) {
- front = 0;
- rear = -1;
- }
- return temp;
- }
- public long peek() {
- if(isEmpty()) {
- System.out.println("Queue is empty. Could not return the first element of the queue.");
- return -10000;
- }
- return queueArray[front];
- }
- public static void main(String[] args) {
- Queue queue = new Queue(5);
- // 1st insert
- System.out .println("After the insert of 10, 20, 30, 40 ,45, 50:");
- queue.insert(10);
- queue.insert(20);
- queue.insert(30);
- queue.insert(40);
- queue.insert(45);
- queue.insert(50);
- queue.printQueue();
- // 1st remove
- System.out.println("After removing the 3 first elements:");
- for(int i=0; i<3; i++) {
- queue.remove();
- }
- queue.printQueue();
- // 2nd insert
- System.out.println("After the insert of 55, 60, 70, 80:");
- queue.insert(55);
- queue.insert(60);
- queue.insert(70);
- queue.insert(80);
- queue.printQueue();
- // 2nd remove
- System.out.println("After removing all the 5 elenments of the queue:");
- for(int i=0; i<queue.size(); i++) {
- queue.remove();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement