Greetings,
I am extremely new to Java and programming in General but I am trying to implement a stack using two queues for a homework assignment. I think I have the right idea but for some reason when the program runs I get:
Exception in thread "main" java.lang.NullPointerException
at com.shadowconcept.mcdougal.StackImplementationUsin gTwoQueues.push(StackImplementationUsingTwoQueues. java:27)
at com.shadowconcept.mcdougal.StackImplementationUsin gTwoQueues.main(StackImplementationUsingTwoQueues. java:57)
Here is the code:
package com.shadowconcept.mcdougal;
import java.util.*;
public class StackImplementationUsingTwoQueues {
Queue<Integer> q1;
Queue<Integer> q2;
public int pop() {
if (q1 == null) {
System.out.println("The stack is empty, nothing to return");
int i = 0;
return i;
}
else {
int temp = q1.remove();
if (q2 != null){
q1.add(q2.remove());
}
return temp;
}
}
public void push(int data){
if (q1 == null){
q1.add(data);
}
else {
q2.add(q1.remove());
q1.add(data);
}
}
public int top(){
if (q1 == null){
int temp = 0;
System.out.println("The Stack is empty returning value 0");
return temp;
}
return q1.peek();
}
public int size(){
if (q1 == null && q2 == null){
int size = 0;
return size;
}
else{
int size = q1.size() + q2.size();
return size;
}
}
public static void main(String[] args) {
StackImplementationUsingTwoQueues s1 = new StackImplementationUsingTwoQueues();
s1.push(8);
s1.push(10);
s1.push(3);
s1.pop();
s1.pop();
}
}