0
내 클래스 중 하나에 대한 프로젝트를 작성 중이며 목적은 스택을 사용하여 대기열을 생성하는 것입니다. 나는 클래스의 일반 프레임 워크를 생각 :내 프로젝트에서 pop() 메소드의 오류가 발생했습니다.
import java.util.LinkedList;
import java.util.Stack;
public class SQueue {
private Stack<Integer> queue;
public SQueue(Stack<Integer> inputQueue) {
queue = inputQueue;
}
public void push(int x) {
Stack<Integer> tempStack = new Stack<Integer>();
Stack<Integer> backwardsStack = new Stack<Integer>();
tempStack.push(x);
while(!queue.isEmpty()) {
backwardsStack.push(queue.pop());
}
while(!backwardsStack.isEmpty()) {
tempStack.push(backwardsStack.pop());
}
queue = tempStack;
}
public int pop() {
Stack<Integer> tempStack = new Stack<Integer>();
while(!queue.isEmpty()) {
tempStack.push(queue.pop());
}
int temp = tempStack.peek();
tempStack.pop();
return temp;
}
public int peek() {
Stack<Integer> tempStack = new Stack<Integer>();
while(!queue.isEmpty()) {
tempStack.push(queue.pop());
}
int temp = tempStack.peek();
return temp;
}
public boolean isEmpty() {
return queue.isEmpty();
}
}
또한 테스트를 위해 다음 클래스 사용하여 임 :
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:102)
at SQueue.pop(SQueue.java:27)
at SQueueTest.case1(SQueueTest.java:19)
at SQueueTest.main(SQueueTest.java:10)
:이 오류를받은 프로그램을 실행 한 후
import java.util.Stack;
public class SQueueTest {
public static void main(String[] args) {
Stack<Integer> s = new Stack<Integer>();
SQueue test1 = new SQueue(s);
SQueue test2 = new SQueue(s);
SQueue test3 = new SQueue(s);
case1(test1);
case2(test2);
case3(test3);
}
public static void case1(SQueue test) {
for(int i =1; i <6; i++) {
test.push(i);
}
for(int i =0; i <3; i++) {
test.pop();
}
System.out.println(test.peek());
}
public static void case2(SQueue test) {
test.push(2);
test.push(4);
test.push(8);
for(int i =0; i <2; i++) {
test.pop();
}
System.out.println(test.isEmpty());
}
public static void case3(SQueue test) {
for(int i = 1; i<4; i++) {
test.push(i*3);
}
test.pop();
System.out.println(test.peek());
System.out.println(test.isEmpty());
}
}
을 이 오류를 해결하는 방법을 잘 모르겠다. pop() 메서드에서 임시 변수를 테스트하는 동안 올바른 int, 5를 저장했지만 그 자리를 제거했기 때문입니다.