Exercise1_3_33
2016-02-05 14:26
183 查看
package chapterone; /*** *@author LuodiJack * *ResizingArrayDeque() 创建空的双向队列 *boolean isEmpty() 双向队列是否为空 *int size() 双向队列的元素数量 *void pushLeft(Item item) 向左端添加一个新元素 *void pushRight(Item item) 向右端添加一个新元素 *Item popLeft() 从左端删除一个元素 *Item popRight() 从右端删除一个元素 * * 测试不完全,如有bug,敬请赐教! */ import java.util.Iterator; public class ResizingArrayDeque<Item> implements Iterable<Item> { private int left; private int right; private Item[] a;// entries private int N;// size @SuppressWarnings("unchecked") public ResizingArrayDeque() { a = (Item[]) new Object[2]; left = 0; right = 1; N = 0; } public boolean isEmpty() { return N == 0; } public int size() { return N; } private void resize(int len) { @SuppressWarnings("unchecked") Item[] tmp = (Item[]) new Object[len]; int i=left, j=tmp.length / 2; for ( ; i < right; i++, j++) { tmp[j] = a[i]; } left=tmp.length / 2; right=j; a = tmp; } public void pushLeft(Item item) { if ((left - 1) < 0) { resize(2 * a.length); } a[left--] = item; N++; } public void pushRight(Item item) { if ((right + 1) >= a.length) { resize(2 * a.length); } a[right++] = item; N++; } public Item popLeft() { if (isEmpty()) { throw new RuntimeException("The Deque is Empty!"); } Item item = a[++left]; a[left] = null;// 防止对象游离 if ((right - left) <= a.length / 4) { resize(a.length / 2); } N--; if (N == 0) { left = right - 1; } return item; } public Item popRight() { if (isEmpty()) { throw new RuntimeException("The Deque is Empty!"); } Item item = a[--right]; a[right] = null;// 防止对象游离 if ((right - left) <= a.length / 4) { resize(a.length / 2); } N--; if (N == 0) { right = left + 1; } return item; } public Iterator<Item> iterator() { return new ResizingArrayDequenIterator(); } private class ResizingArrayDequenIterator implements Iterator<Item> { private int i = left; public boolean hasNext() { return (i + 1) < right; } public Item next() { return a[++i]; } } }
相关文章推荐
- 装IIS时遇到一个Server Application Error错误解决
- 计算机网络体系结构
- chmod 命令
- Ubuntu14.04无线上网不稳定,掉线之后无法重连上网解决。
- [LeetCode][JavaScript]Verify Preorder Serialization of a Binary Tree
- codevs 1227 方格取数2
- this方法获取a标签ID值及内容;idx传参
- poj2262 2010.2.17
- [转] JAVA resultset
- Delphi中如何获得光标
- 高精度 A-B Problem
- poj1061 2010.2.17
- poj1503 2010.2.17
- POJ 2482 线段树+离散化
- [转] 编程语言解惑:学.Net还是学Java
- js前端分页
- freemarker中include与import的区别
- 一个单元测试问题的解决
- 计算机网络的结构组成
- PAT1003.我要通过!