用数组结构实现大小固定的队列和栈-java实现

1,用数组实现大小固定的栈

栈的特点是先进后出,所以用数组实现栈时,只需要利用一个指针判定数据存储的位置即可,添加元素时判断指针是否超过数组长度,如果没有越界将元素添加到指针所指的位置,并将指针向右移位一格;否则返回异常,显示栈空间已满。删除元素思路类似,判断指针是否为数组初始位置,不是则将指针所指元素左边的元素返回,并将指针向左移位一格。

代码实现如下:

public class MyStack {

	private int[] arr;
	private int size;
	public MyStack( int startsize) throws Exception {
		if(startsize<0){
			throw new Exception("输入有误");
		}
		arr = new int[startsize];
		size = 0;
	}
	
	public void push(int num) throws Exception{
		if(size == arr.length){
			throw new Exception("the stack is full!");
		}
		arr[size++] = num;
	}
	
	public int pop() throws Exception{
		if(size == 0){
			throw new Exception("the stack is empty!");
		}
		return arr[--size];
	}
	
	public int peek() throws Exception{
		if(size == 0){
			throw new Exception("the stack is empty!");
		}
		return arr[size-1];
	}

	public boolean isEmpty(){
		return size>0?false:true;
	}

	public static void main(String[] args) throws Exception {
		
		MyStack ms = new MyStack(10);
		ms.push(1);
		ms.pop();
		ms.push(2);
		ms.push(3);
		ms.push(4);
		ms.push(5);
		ms.push(2);
		ms.pop();
		ms.push(3);
		ms.push(4);
		ms.push(5);
		ms.push(2);
		ms.push(3);
		while(!ms.isEmpty()){
			System.out.println(ms.pop());
		}
	}
}

2,用数组结构实现大小固定的队列

队列的特点是先进先出"FIFO",所以用数组实现队列操作时,我们需要利用三个变量对数组进行操作,First指针用于记录先进队列的数据,Last指针始终指向存入数据的下个位置,如果指针越界则返回0点。Size用于记录队列中元素的个数,加入元素时需要先判断Size大小是否超过数组的长度,如果超出则抛出异常显示队列已满,反之则将元素添加至Last指针所指的位置,并将Last指针移位(需要判断是否发生指针越界)。
流程图如下所示:

在这里插入图片描述

实现代码如下:

public class MyQueue {

	private int[] arr;
	private int first;
	private int last;
	private int size;
	
	public MyQueue(int initsize) throws Exception{
		if(initsize<0){
			throw new Exception("Input Error!!!");
		}
		arr = new int[initsize];
		first = 0;
		last = 0;
		size = 0;
	}
	
	public void push(int num) throws Exception{
		if(size == arr.length){
			throw new Exception("The Queue is full!!!");
		}
		arr[last] = num;
		last = last==arr.length-1?0:last+1;
		size++;
	}
	
	public int poll() throws Exception{
		if(size<1){
			throw new Exception("The Queue is empty!!!");
		}
		int temp = first;
		first = first==arr.length-1?0:first+1;
		size--;
		return arr[temp];
	}
	
	public int peek() throws Exception{
		if(size<1){
			throw new Exception("The Queue is empty!!!");
		}
		return arr[first];
	}
	
	public boolean isEmpty(){
		return size<1?true:false;
	}
	
	public static void main(String[] args) throws Exception {
		
		MyQueue mq = new MyQueue(5);
		mq.push(1);
		mq.push(2);
		mq.push(3);
		mq.poll();
		mq.push(4);
		mq.push(5);
		
		while(!mq.isEmpty()){
			System.out.println(mq.poll());
		}

	}

}

猜你喜欢

转载自blog.csdn.net/justlikeu777/article/details/83788298
今日推荐