Implementing Stack and queues in Java

//Implementing a queue (FIFO) first in first out

 

public class queue {

 

Object[] array;

int start, end;

 

public queue(int c)

{

array = new Object[c];

start = end =0;

 

}

 

public void add(Object a)

{

array[start = (++start % array.length)] = a;

System.out.println(“Added to queue: “+array[start]);

}

public void remove()

{

System.out.println(“Removed: “+array[end = (++end % array.length)] );

array[end = (++end % array.length)] = null;

 

 

}

}

 

 

**********************************************

//Implementing a stack

 

 

public class stack {

 

Object[] array;

int pointer = -1;

//Constructor to initiaize the array i.e. stack

 

 

public stack(int c) {

int capacity = c;

array = new Object[capacity];

}

 

//Adding a object to array

public void add ( Object a){

 

pointer++;

array[pointer] = a;

System.out.println(“Pushed: “+a);

}

 

//As it is LIFO you do not need to ask which object to remove

public void remove()

{

System.out.println(“Removed: ” +array[pointer]);

array[pointer] = null;

pointer–;

 

}

}

 

************************************

//Tester class to test the program

 

 

 

public class stacktest {

 

public static void main(String [] args)

{

System.out.println(“Starting stack implementation LIFO”);

stack s = new stack(10);

s.add(1);

s.add(2);

s.add(3);

s.add(4);

s.remove();

s.add(5);

 

System.out.println(“Starting queue implementation FIFO”);

queue q = new queue(10);

q.add(1);

q.add(2);

q.add(3);

q.add(4);

q.remove();

q.add(5);

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s