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

public class Array_to_Stack_and_Queue{
	public static class ArrayStack{
		private int[] arr;
		private int index;
		
		public ArrayStack(int initSize) {
			if(initSize < 0) {
				System.out.println("the init size is less than 0");
			}
			arr = new int[initSize];
			index = 0;
		}
		
		public void push(int obj) {
			if(index == arr.length) {
				System.out.println("the stack is full");
			}
			arr[index++] = obj;
		}
		
		public int pop() {
			if(index == 0) {
				System.out.println("the stack is empty");
			}
			return arr[--index];
		}
		
		public int peek() {
			if(index == 0) {
				System.out.println("the stack is empty");
			}
			return arr[index - 1];
		}
		
		public void printStack() {
			for(int i = index-1; i >=0; i--) {
				System.out.println(arr[i]);
			}
			System.out.println("------");
		}
	}
	
	public static class ArrayQueue{
		private int[] arr;
		private int size;
		private int head;
		private int tail;
		
		public ArrayQueue(int initSize) {
			if(initSize < 0) {
				System.out.println("The init queue size is less then 0");
			}
			arr = new int[initSize];
			size = 0;
			head = 0;
			tail = 0;
		}
		
		public void push(int obj) {
			if(size >= arr.length) {
				System.out.println("the queue is full");
				return;
			}
			size++;
			arr[tail] = obj;
			tail = (tail == arr.length-1) ? 0 : tail + 1;
		}
		
		public int pop() {
			if(size == 0) {
				System.out.println("the queue is empty");
			}
			size--;
			int temp = head;
			head = (head == arr.length - 1) ? 0 : head + 1;
			return arr[temp];	
		}
		
		public int peek() {
			if(size == 0) {
				System.out.println("the queue is empty");
			}
			return arr[head];
		}
	}
	
	public static void main(String[] args) {
		ArrayStack stack1 = new ArrayStack(4);
		ArrayQueue queue1 = new ArrayQueue(4);
		
		stack1.push(1);
		stack1.push(2);
		stack1.push(3);
		stack1.push(4);
		
		queue1.push(1);
		queue1.push(2);
		queue1.push(3);
		queue1.push(4);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值