implement a queue using two stacks - java

I think my codes are right, but i do not know why it is not adding elements onto the stack.
Should i create other two stacks in the main?
import java.util.Stack;
public class stacks {
public Stack<Integer> in = new Stack<Integer>();
public Stack<Integer> out = new Stack<Integer>();
public void enqueue(int value){
in.push(value);
}
public int dequeue(){
if (out.isEmpty()){
while(!in.isEmpty()){
out.push(in.pop());
}
}
return out.pop();
}
public static void main(String[] args) {
in.enqueue(10);
in.enqueue(49);
}
}

Your code is absolutely correct. You have missed one small thing.
You are pushing elements in stack 1 during enqueue.
During dequeue, you are popping elements from stack 1 and pushing in stack 2. Then you are popping the top element from stack 2 .
(1).
The stuff that you are missing is. Popping all the elements back from stack 2 and pushing them to stack 1. So, here is what I suggest you to do :
public int dequeue(){
if (out.isEmpty())
{
while(!in.isEmpty())
{
out.push(in.pop());
}
}
int outVar = out.pop();
while(!out.isEmpty())
{
in.push(out.pop());
}
return outVar;
}
(2). In the main method. You do not have to create two different stacks. You just have to create an object of you class Stacks. which would solve the purpose.
public static void main(String[] args) {
Stacks obj = new Stacks();
obj.enqueue(10); // Would enqueue 10 in the Stack 1 of the Object 'obj'
obj.enqueue(49);
System.out.println(obj.dequeue());// Would display the dequeued element.
}
Hope this helps.

Your issue here is that you are trying to make a static reference (from the main) to something that isn't static.
Make the following changes:
public static int dequeue()
public static void enqueue(int value)
A workaround to this would be to make an object oriented stack-queue class and then in a separate class make an instance of that stack-queue class. This would eliminate any static referential issues and also bring your program up to par with today's common object-oriented programming standards. Like so:
import java.util.Stack;
public class stacksTest {
public Stack<Integer> in = new Stack<Integer>();
public Stack<Integer> out = new Stack<Integer>();
public void enqueue(int value){
in.push(value);
}
public int dequeue(){
if (out.isEmpty()){
while(!in.isEmpty()){
out.push(in.pop());
}
}
return out.pop();
}
}
Then make a new class:
public class Test {
public static void main(String[] args) {
stackTest st = new stackTest();
st.enqueue(10);
st.dequeue(10);
}
}

Related

Trying to increment local variable from a separate method but not working. Confusion about Activation Stack/Record

public class Demo {
public static void main(String[] args){
Demo instance = new Demo();
instance.init();
}
public void init() {
int size = 0;
inc(size);
System.out.println(size);
}
public int inc(int size){
size++;
return size;
}
}
When I call the code above, the number zero is returned.
Even declaring size as a class attribute instead of a local variable does not solve the problem. I understand that when a method is complete, the corresponding record (containing local variable and such) is popped off of the activation stack. But, if the size variable is declared in the init() method, and then incremented and returned in a separate method (inc()), shouldn't size be equal to 1?
When incrementing you do not assign the value to anything, it increments it, but it does not store it anywhere so the value remains 0, try doing like this.
public class Demo
{
public static void main(String[] args)
{
Demo instance = new Demo();
instance.init();
}
public void init()
{
int size = 0;
size = inc(size);
System.out.println(size);
}
public int inc(int size)
{
size++;
return size;
}
}
or like this
public class Demo
{
public static void main(String[] args)
{
Demo instance = new Demo();
instance.init();
}
public void init()
{
int size = 0;
System.out.println(inc(size));
}
public int inc(int size)
{
size++;
return size;
}
}
size = inc(size);
will solve your problem, since you are not using a public scoped variable.
If you want to make this a bit elegant (at least I think this will be a bit more handy), then you need to declare a variable as a class variable.
I will illustrate this to you:
public class Demo {
int size; //global range variable
public static void main(String[] args){
Demo instance = new Demo();
instance.init();
}
public void init() {
this.size = 0;
inc();
System.out.println(this.size);
}
public void inc(){
this.size++; //will increment your variable evertime you call it
}
}

Simple Stack, how to initialize Node at 0 instead of null

I am trying to implement a very simple stack, however, it seems that I need to use a node for this. I have the below which compiles and works fine, however, it throws a lot of errors until someone makes the first push. I am in a situation where I cannot control what is in the consumer's main method, so I think it would be best to avoid these errors and just initialize a new stack object with an initial value of zero. Unfortunately, I cannot figure out just how to do that. Would anyone here be able to advise me?
import java.util.*;
public class StackQ {
Node top;
public StackQ() {
top=null;
}
class Node {
public int x = 0;
public Node next;
Node(int d) {x=d; next=null;}
public int getData() {return x;}
}
public int pop() {
if(top!=null) {
int item = top.x;
top = top.next;
return item;
}
return -1;
}
public void push(int x) {
Node t = new Node(x);
t.next = this.top;
this.top = t;
}
public int top() {
if (top == null) throw new EmptyStackException();
return top.x;
}
public static void main(String[] args) {
StackQ mainStack = new StackQ();
}
}
If they're using top() without putting anything in the stack, they are using your stack wrong. Seriously, they should be getting an exception. It's up to them to not use your stack that way, and it's up to them to properly handle that exception.
But if you really wanted to always start your stack with a 0 in it (which, to be perfectly clear, I am advising against doing) just put that in your constructor.
public StackQ() {
top=new Node(0);
}

How to initialise and access an array of collection objects

I want to create an array of sets and access them for my program. But, since arrays cannot be merged with generic types, I have wrapped my HashSet class inside another class as given below.
Class MyClass{
private HashSet<Integer> myKeys;
public boolean add(Integer i) { return myKeys.add(i); }
public boolean contains(Integer i){ return myKeys.contains(i); }
public boolean remove(Integer i){ return myKeys.remove(i); }
}
Later in my main() method, I had put the below code:
public static void main(String []args){
System.out.println("Hello World");
MySets[] keys= new MySets[2];
keys[1].add(1);
keys[2].add(2);
keys[1].add(2);
keys[2].add(4);
System.out.println("Key 1=" +keys[1]+" Key 2=" +keys[2]);
}
I am unable to access any of the objects may be since they are not initialised as HashSets. Please suggest a possible solution to access the sets.
The objects on the array are null since you didn't initialize them.
You have to initialize them first.
You also have to initialize your HashSet.
You should work with the Set interface instead HashSet.
There's also a problem with the indexes of your array. Java indexes start from 0.
class MySets {
private Set<Integer> myKeys = new HashSet<Integer>();
public boolean add(Integer i) { return myKeys.add(i); }
public boolean contains(Integer i){ return myKeys.contains(i); }
public boolean remove(Integer i){ return myKeys.remove(i); }
}
public static void main(String []args){
System.out.println("Hello World");
MySets[] keys= new MySets[2];
keys[0] = new MySets();
keys[1] = new MySets();
keys[0].add(1);
keys[1].add(2);
keys[0].add(2);
keys[1].add(4);
System.out.println("Key 1=" +keys[0]+" Key 2=" +keys[1]);
}

memory management using linked list

This is a homework question in relation to memory management implementation using linked lists.
Each memory process requests of a particular size of memory that must be contiguously large enough to fit the memory and then allocate the process.When a job terminates,its allowed memory becomes free.
This is the java code I wrote for this.
public class PartitionNode{
int beginAddress;
int endAddress;
boolean holeFree;
int processId;
PartitionNode next;
public PartitionNode(int begin,int end){
beginAddress=begin;
endAddress=end;
holeFree=true;
processId=-1;
next=null;
}
public PartitionNode(){}
public PartitionNode(int begin,int end,int i){
beginAddress=begin;
endAddress=end;
holeFree=false;
processId=i;
}
}
public class Partition{
private PartitionNode head;
public PartitionNode current;
public int begin;
public int end;
public PartitionNode newPartition;
public Partition(int beginAddress,int endAddress,int a){
head=new PartitionNode(beginAddress,endAddress);
begin=beginAddress;
end=endAddress;
current=head;
}
public Partition(int beginAddress,int endAddress){
current=new PartitionNode(beginAddress,endAddress);
}
public void addProcess(int size,int id){
if((current.endAddress-current.beginAddress>=size)&& current.holeFree==true){
newPartition=new PartitionNode(current.beginAddress,current.beginAddress+size-1,id);
newPartition.next=refresh();
System.out.println("beginAddress"+newPartition.beginAddress);
System.out.println("endAddress"+newPartition.endAddress);
}
}
public void print(){
System.out.println("beginAddress"+newPartition.beginAddress);
System.out.println("endAddress"+newPartition.endAddress);
}
public PartitionNode refresh(){
current=new PartitionNode(newPartition.endAddress+1,end);
return current;
}
public void deleteProcess(int process){
PartitionNode temp=head;
while(temp.next!=null){
System.out.println(temp.processId);
temp=temp.next;
}
}
public static void main (String args[]){
Partition p=new Partition(300,3000,1);
p.addProcess(500,1);
p.addProcess(800,2);
p.addProcess(400,3);
p.deleteProcess(5);
System.out.println(p.head.beginAddress);
}
}
I have two questions.
I have to have a constructor as
public Partition(int beginAddress,int endAddress,int a){
head=new PartitionNode(beginAddress,endAddress);
begin=beginAddress;
end=endAddress;
current=head;
}
where int a is of no use.It is just there to make sure that this constructor's argument list is different from
public Partition(int beginAddress,int endAddress){
current=new PartitionNode(beginAddress,endAddress);
}
Because of this now I have to call as Partition p=new Partition(300,3000,1); with 1 being useless.
How can I get rid of this problem.
My next question is implementing method to delete a process.
public void deleteProcess(int process){
PartitionNode temp=head;
while(temp.next!=null){
System.out.println(temp.processId);
temp=temp.next;
}
}
The while loop doesn't get executed.What's wrong with that?
Can someone please help me to correct the mistakes?
Comment-as-answer:
You should split this into two questions. You can get rid of the need for the useless concstructor arg by using static factory methods to create your object, rather than the constructor directly. They allow you to name different ways to create an instance of a class. Make the constructor private while having public static methods that return a new instance of the class. That will allow you to use the same parameters for a "constructor", while having the ability to create and return a unique instance:
class Example {
public static void main(String[] args) {
Object first = Object.createObject(1, 2);
Object second = Object.createAndStore(1, 2);
}
}
class Object {
private int a, b;
//private constructor ensures need for methods
private Object(int a, int b) {
//create node
}
//the factory methods
public static Object createObject(int a, int b) {
return new Object(a, b);
}
public static Object createAndStore(int a, int b) {
Object ob = new Object();
//store vars using ob
return ob;
}
}
As for the loop part, where do you init temp.next? I see you initialize temp with head, but I don't see where you initialize it.
Also, I highly suggest changing the title of this question to more fit the issues

java stack NullPointerException

I have a class Floor which has a Stack of Blocks and I don't know how to initialize it. I had tried like this:
public class Floor {
private Stack<Block> stack;
private static int size;
public void setStack(Stack<Block> stack) {
this.stack = stack;
}
public void addBlock(Block b){
stack.push(b);
}
}
public class InputDevice {
Block a0=new Block('I',false);
Floor [] floor=new Floor[5];
Stack<Block> stack=new Stack<Block>();
floor[0].setStack(stack);
floor[0].addBlock(a0);
}
Floor [] floor=new Floor[5];
you declared the array, but you didn't init the elements, then :
floor[0].setStack(stack); floor[0] is null, npe!
also I suggest that in your Floor class, addBlock(Block b) method, check if the stack is null, if it is null, otherwise it would have problem(NPE) if someone init Floor, and directly floor.addBlock(b).
You've not initialized any of the Floor objects in the array yet. When you create an array of objects it's like creating an egg carton. You can't use any eggs until you put some in the carton first. You can't use any objects in the array before you've initialized them, which is often done within a for loop. i.e.,
Floor [] floor=new Floor[5];
for (int i = 0; i < floor.length; i++) {
floor[i] = new Floor();
}
try this code
public class Floor {
private Stack<Block> stack;
private static int size;
public void setStack(Stack<Block> stack) {
this.stack = stack;
}
public void addBlock(Block b){
stack.push(b);
}
}
public class InputDevice {
Block a0=new Block('I',false);
Floor [] floor=new Floor[5];
floor[0] = new Floor();
Stack<Block> stack=new Stack<Block>();
floor[0].setStack(stack);
floor[0].addBlock(a0);
}

Categories