week 2:用数组结构实现大小固定的队列和栈

topic requirement:

           无

thoughts:

   对于用数组结构实现大小固定的栈:有初始化栈、入栈、出栈、返回栈顶等功能

  •     提供变量size,用来记录栈中元素的数量。入栈+1,出栈-1。

   对于用数组结构实现队列:有初始化队列、进队列,出队列等操作

  • 定义变量start用来记录最早进入队列的元素下标,定义变量end用来记录后面进来元素的下标,size用来记录队列中元素的数目

 code:

public class Array_To_Stack_Queue {
	
	public static class ArrayStack {
		private Integer[] arr; 
		private Integer size;  

		public ArrayStack(int initSize) {
			if (initSize < 0) {
				throw new IllegalArgumentException("The init size is less than 0");
			}
			arr = new Integer[initSize];  
			size = 0;  
		}

		public Integer peek() { 
			if (size == 0) {
				return null;
			}
			return arr[size - 1]; 
		}

		public void push(int obj) { 
			if (size == arr.length) {  
				throw new ArrayIndexOutOfBoundsException("The queue is full");
			}
			arr[size++] = obj;  
		}

		public Integer pop() { 
			if (size == 0) {
				throw new ArrayIndexOutOfBoundsException("The queue is empty");
			}
			return arr[--size];
		}
	}

	public static class ArrayQueue {
		private Integer[] arr;
		private Integer size;
		private Integer start;
		private Integer end;

		public ArrayQueue(int initSize) {
			if (initSize < 0) {
				throw new IllegalArgumentException("The init size is less than 0");
			}
			arr = new Integer[initSize];
			size = 0;
			start = 0;
			end = 0;
		}

		public Integer peek() { 
			if (size == 0) {
				return null;
			}
			return arr[start];
		}

		public void push(int obj) {
			if (size == arr.length) {
				throw new ArrayIndexOutOfBoundsException("The queue is full");
			}
			size++;
			arr[end] = obj;
			end = end == arr.length - 1 ? 0 : end + 1;
		}

		public Integer poll() {
			if (size == 0) {
				throw new ArrayIndexOutOfBoundsException("The queue is empty");
			}
			size--;
			int tmp = start;
			start = start == arr.length - 1 ? 0 : start + 1;
			return arr[tmp];
		}
	}
 
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(3);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println("-----------------");
        
        ArrayQueue queue = new ArrayQueue(3);
        
        queue.push(1);
        queue.push(2);
        queue.push(3);
        
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
		
	}

}

 reference:左神   

encouragement:  

   生活中总是充满了选择和矛盾,请一定审视一下自己的内心,去争取那最珍贵的东西,可惜我一直做不到。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

const

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值