0
누군가 내가 뭘 잘못 설명하고 있습니까? 책 연습으로 두 개의 스택에서 대기열을 만들려고합니다. peek 함수에서 "Stack Underflow"오류가 발생합니다. 그러나 모든 것이 제게 옳은 것처럼 보입니다. P 제발 설명해주세요. 감사!두 개의 스택에서 대기열 생성
//Program to implement Queue using two Stacks.
import java.util.NoSuchElementException;
public class Ex3_5_Stack {
int N;
int countOfNodes=0;
private Node first;
class Node {
private int item;
private Node next;
}
public Ex3_5_Stack() {
first=null;
N=0;
}
public int size() {
return N;
}
public boolean isEmpty() {
return first==null;
}
public void push(int item){
if (this.countOfNodes>=3) {
Ex3_5_Stack stack = new Ex3_5_Stack();
stack.first.item=item;
N++;
} else {
Node oldfirst = first;
first = new Node();
first.item=item;
first.next=oldfirst;
N++;
}
}
public int pop() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
int item = first.item;
first=first.next;
return item;
}
public int peek() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
return first.item;
}
}
그리고 transferStack()
에서
public class Ex3_5_MyQueue {
Ex3_5_Stack StackNewest,StackOldest;
public Ex3_5_MyQueue() {
super();
StackNewest = new Ex3_5_Stack();
StackOldest = new Ex3_5_Stack();
}
public int size() {
return StackNewest.size()+StackOldest.size();
}
public void add(int value) {
StackNewest.push(value);
}
private void transferStack() {
if (StackOldest.isEmpty()) {
while (StackNewest.isEmpty()) {
StackOldest.push(StackNewest.pop());
}
}
}
public int peek() {
this.transferStack();
return StackOldest.peek();
}
public int remove() {
this.transferStack();
return StackOldest.pop();
}
public static void main(String[] args) {
Ex3_5_MyQueue myQueue = new Ex3_5_MyQueue();
myQueue.add(4);
myQueue.add(3);
myQueue.add(5);
myQueue.add(1);
System.out.println(myQueue.peek());
}
}
또 왜'push()'코드의'if (this.countOfNodes> = 3)'절을 사용합니까? 새 스택을 만들고 거기에 항목을 밀어 넣은 다음 새 스택을 저장하지 않기 때문에 카운트가 1 씩 증가했지만 이전 항목 만 있으면됩니다. –
감사합니다! 다른 관련 프로그램을위한 것입니다. 위에서 언급 한 목적과의 관련성이 없습니다. – CtrlV
당신이 그렇게 말하면, 그것이 무엇이든 희망을 품기는하지만 그것이 문서화되어 있기 때문에 그렇게하는 이유를 알 수 있습니다. –