java - Creating queue from two stacks -
can explain doing wrong here ? trying create queue 2 stacks per book exercise. error "stack underflow" peek function. seems right me :p please explain. thanks!
//program implement queue using 2 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; } }
and myqueue file
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()); } }
in transferstack()
, you're missing exclamation mark. should be:
private void transferstack(){ if(stackoldest.isempty()){ while(!stacknewest.isempty()){ // forgot here stackoldest.push(stacknewest.pop()); } } }
Comments
Post a Comment