CareerCup 14.6

来源:互联网 发布:嵌入式linux原理 编辑:程序博客网 时间:2024/05/05 14:14

Implement Circular Array


/* * Career Cup 14.6 *  */package CareerCup;import java.util.Iterator;public class CircularArray<T> implements Iterable<T> {private T items[];private int head;public CircularArray(int size) {items = (T[]) new Object[size];head = 0;}public int Size() {return items.length;}public void rotate(int rightShift) {if (rightShift < 0) {rightShift += items.length;}head = (head + rightShift) % items.length;}public int convert(int index) {int i = (index + head) % items.length;return i;}public T get(int index) {if (index < 0 || index >= items.length) {throw new java.lang.IndexOutOfBoundsException();}int i = convert(index);return items[i];}public void set(int index, T item) {int i = convert(index);items[i] = item;}@Overridepublic Iterator<T> iterator() {return new CircularArrayIterator<T>(this);}private class CircularArrayIterator<TI> implements Iterator<TI> {private int current = -1; //current reflects the offset from the rotated headprivate TI[] refItems;public CircularArrayIterator(CircularArray<TI> c) {refItems = c.items;}@Overridepublic boolean hasNext() {return current < refItems.length - 1;}@Overridepublic TI next() {current++;int i = convert(current);return refItems[i];}@Overridepublic void remove() {throw new UnsupportedOperationException();}}/** * @param args */public static void main(String[] args) {CircularArray<Integer> arr;arr = new CircularArray<Integer>(5);for(int i = 0; i < arr.Size(); i++) {Integer in = new Integer(i + 10);arr.set(i, in);}System.out.println("Before rotate...");for(Integer i : arr) {System.out.println(i);}System.out.println("After rotated...");arr.rotate(2);for(Integer i : arr) {System.out.println(i);}}}


原创粉丝点击