View Single Post
  #1 (permalink)  
Old 01-29-2008, 12:53 AM
rhm54 rhm54 is offline
Member
 
Join Date: Jan 2008
Posts: 12
rhm54 is on a distinguished road
Implementing a Stack Using two Queues
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:

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(); } }
Reply With Quote
Sponsored Links