package question.stackqueue;
public class MyQueue {
/* Main */
public static void main(String[] args) {
Queue<Integer> queue = new Queue(16);
queue.add(1);
queue.add(2);
queue.add(3);
System.out.println(queue.remove());
System.out.println(queue.remove());
System.out.println(queue.remove());
System.out.println(queue.remove());
}
/* Queue - RingBuffer구현 */
public static class Queue<T> {
// == Field ==
public int capacity;
public int pointerFront;
public int pointerBack;
public int size;
public T[] bucket;
// == Constructor ==
public Queue(int capacity) {
this.capacity = capacity;
this.pointerBack = 0;
this.pointerFront = 0;
this.size = 0;
this.bucket = (T[]) new Object[capacity]; // * 제네릭객체 생성방법
}
// == add ==
public void add(T t) {
if(size < capacity) {
this.bucket[pointerFront++] = t;
size++;
if(pointerFront >= capacity) pointerFront = 0;
}
}
// == remove ==
public T remove() {
if(size > 0) {
size--;
T rtn = this.bucket[pointerBack++];
if(pointerBack >= capacity) pointerBack = 0;
return rtn;
}
return null;
}
// == peek ==
public T peek() {
if(size > 0) {
return this.bucket[pointerBack];
}
return null;
}
// == isEmpty ==
public boolean isEmpty() {
return size == 0 ? true : false;
}
}
}
public class MyQueue {
/* Main */
public static void main(String[] args) {
Queue<Integer> queue = new Queue(16);
queue.add(1);
queue.add(2);
queue.add(3);
System.out.println(queue.remove());
System.out.println(queue.remove());
System.out.println(queue.remove());
System.out.println(queue.remove());
}
/* Queue - RingBuffer구현 */
public static class Queue<T> {
// == Field ==
public int capacity;
public int pointerFront;
public int pointerBack;
public int size;
public T[] bucket;
// == Constructor ==
public Queue(int capacity) {
this.capacity = capacity;
this.pointerBack = 0;
this.pointerFront = 0;
this.size = 0;
this.bucket = (T[]) new Object[capacity]; // * 제네릭객체 생성방법
}
// == add ==
public void add(T t) {
if(size < capacity) {
this.bucket[pointerFront++] = t;
size++;
if(pointerFront >= capacity) pointerFront = 0;
}
}
// == remove ==
public T remove() {
if(size > 0) {
size--;
T rtn = this.bucket[pointerBack++];
if(pointerBack >= capacity) pointerBack = 0;
return rtn;
}
return null;
}
// == peek ==
public T peek() {
if(size > 0) {
return this.bucket[pointerBack];
}
return null;
}
// == isEmpty ==
public boolean isEmpty() {
return size == 0 ? true : false;
}
}
}
반응형
'CS > 자료구조 구현' 카테고리의 다른 글
구현 // 자료구조 // 스택(Stack) // toJava (0) | 2018.08.02 |
---|