데이터 구조 - 07 대기 열
2010 단어 데이터 구조
package org.gzw.ch03;
/**
*
*/
public class MyQueue {
//
private long[] arr;
//
private int elements;
//
private int front;
//
private int end;
/**
*
*/
public MyQueue(){
arr = new long[10];
elements = 0;
front = 0;
end = -1;
}
/**
*
*/
public MyQueue(int maxsize){
arr = new long[maxsize];
elements = 0;
front = 0;
end = -1;
}
/**
* ,
*/
public void insert(long value){
arr[++end] = value;
elements++;
}
/**
* , ???
*/
public long remove(){
elements--;
return arr[front++];
}
/**
* ,
*/
public long peek(){
return arr[front];
}
/**
*
*/
public boolean isEmpty(){
return elements == 0;
}
/**
*
*/
public boolean isFull(){
//return (end - front) == arr.length;
return elements == arr.length;
}
}
2. 테스트:
package org.gzw.ch03;
public class TestMyQueue {
public static void main(String[] args) {
MyQueue myQueue = new MyQueue(4);
myQueue.insert(23);
myQueue.insert(45);
myQueue.insert(13);
myQueue.insert(1);
System.out.println(myQueue.isEmpty());
System.out.println(myQueue.isFull());
System.out.println(myQueue.peek());
System.out.println(myQueue.peek());
while(!myQueue.isEmpty()){
System.out.print(myQueue.remove() + ", ");
}
System.out.println();
System.out.println(myQueue.isFull());
System.out.println(myQueue.isEmpty());
// , end , 。
myQueue.insert(20);
}
}
3. 실행 결과:
false
true
23
23
23, 45, 13, 1,
false
true
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at org.gzw.ch03.MyQueue.insert(MyQueue.java:39)
at org.gzw.ch03.TestMyQueue.main(TestMyQueue.java:24)
4. 오류 원인: insert (20) 후 end 매개 변 수 는 배열 의 마지막 위치 에 있 습 니 다. 추가 하면 넘 칩 니 다. 처리 방법: 다음 순환 대기 열 MyCycleQueue 를 보십시오.