队列

手写扩容队列

	public static class ArrayQueue {
		int n;
		int tail = 0;
		int head = 0;
		String[] queue;

		public ArrayQueue(int capacity) {
			this.n = capacity;
			queue = new String[capacity];
		}

		public void enqueue(String s) {
			if (tail == n) {
				String[] temp = new String[(int) (1.5 * queue.length)];
				for (int i = 0; i < queue.length; i++) {
					temp[i] = queue[i];
				}
				queue = temp;
			}
			queue[tail] = s;
			tail ++;
		}

		public String dequeue() {
			if (head == tail){
				return null;
			}
			else{
				String 	ret = queue[head];
				head ++;
				return ret;
			}
		}
	}

循环队列一:数据搬移类型

	public static class CycleQueue {
		String[] queue;
		int n;
		int head;
		int tail;

		public CycleQueue(int n) {
			this.n = n;
			queue = new String[n];
		}

		public boolean enqueue(String s) {
			if (tail == n) {
				if (head == 0) {
					return false;
				}
				for(int i = head ; i < tail ; i ++){
					queue[i-head] = queue[i];
				}
				tail = tail - head;
				head = 0;
				
			}
			queue[tail] = s;
			tail++;
			return true;
		}

		public String dequeue() {
			if (head == tail) {
				return null;
			}
			String res = queue[head];
			head++;
			return res;
		}

	}

循环队列二:循环head/tail
重点确定好队空和队满的判定条件
这里,浪费了数组的一个存储空间,作为队满队空的判断条件。

public static class CycleQueue2{
		String[] queue;
		int n;
		int head;
		int tail;

		public CycleQueue2(int n) {
			this.n = n;
			queue = new String[n];
		}

		public boolean enqueue(String s) {
			if ((tail + 1) % n == head) {
				return false;
			}
			queue[tail] = s;
			tail = (tail + 1) % n;
			return true;
		}

		public String dequeue() {
			if(tail == head){
				return null;
			}
			String res = queue[head];
			head = (head + 1) % n;
			return res;
		}
	}

链式队列

public static class LinkQueue{
	 Queue head ;
	 Queue prev;
	 public void enqueue(String s){
		 Queue queue = new Queue();
		 queue.data = s;
			if (prev != null) {
				prev.next = queue;
				prev = queue;
			} else {
				prev = queue;
				head = queue;
			}
	 }
		 
		public String dequeue() {
			if (head != null) {
				String res = head.data;
				if (head.next != null) {
					head = head.next;
				} else {
					head = null;
				}
				return res;
			}
			return null;
		}
		 
	}
	
	public static class Queue{
		public String data;
		public Queue next;

		public String toString() {
			return data;
		}
		 
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值