Design a class named Queue for storing integers. Like a stack, a queue holds elements. In a stack,

1>Design a class named Queue for storingintegers. Like a stack, a queue holds elements. In a stack, the elements areretrieved in a last-in first-out fashion. In a queue, the elements are

retrieved in a first-in first-out fashion.The class contains:

■  An int[] data fieldnamed  elements that stores the  int values in the queue.

■  A data field named  size that stores the number of elements inthe queue.

■  A constructor that createsa  Queue object with defaultcapacity  8 .

■  The method  enqueue(int v) that adds  v into the queue.

■  The method  dequeue() that removes and returns theelement from the queue.

■  The method  empty() that returns true if the queue isempty.

■  The method  getSize() that returns the size of the queue.

Implement the class with the initial arraysize set to 8. The array size will be doubled once the number of the elementsexceeds the size. After an element is removed from the beginning of thearray,you need to shift all elements in the array one position the left. Writea test program that adds 20 numbers from 1 to 20 into the queue and removesthese numbers and displays them.

import java.util.Arrays;

public class Queue {
	int[] elements;
	int size;
  
	public Queue() {
		this.elements = new int[8];
		this.size = 0;
	}
	
	public void enqueue(int v) {  
		if(!(this.size <= this.elements.length))
			doubleSize();
			this.size++;
			elements[this.size-1] = v;
	}
  
	public int dequeue() {
		if(!this.empty()) {
			this.size--;
			int ret=this.elements[0];
			shiftElements();
			return ret;
		}
		return -1;
	}
	
	public boolean empty() {
		if(this.size==0)
			return true;
		else
			return false;
	}
	
	public int getSize() {
		return this.size;
	}
  
	private void doubleSize() {
		int[] test=new int[this.elements.length*2];
		for(int i=0;i<test.length;i++) {
			if(i<this.elements.length)
				test[i]=this.elements[i];
			else 
				test[i]=0;
		}		
		this.elements=test;
	}
	
	private void shiftElements() {
		for(int i=0;i<=size;i++) {
			if(i<this.elements.length)
				this.elements[i]=this.elements[i+1];
			else 
				this.elements[i]=0;
		}
	}
  

public static void main(String[] args) {
	Queue q=new Queue();
	System.out.println("Initial queue's size: "+q.getSize());
	q.enqueue(1);
	q.enqueue(2);
	System.out.println("Queue size after adding 2 elements: "+q.getSize());
	System.out.println("Elements: "+Arrays.toString(q.elements));
	System.out.println("Dequing: "+q.dequeue());
	System.out.println("Size after dequeue: "+q.getSize());
	System.out.println("Elements after dequeue: "+Arrays.toString(q.elements));
	}
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值