Stacks
In Stacks you can only add (or also called "push") and a new item in the very end of the Array. And you can only delete (or also called "pop") the last item of the Array. this is called Last-In-First-Out (LIFO).Here's the push implementation:
public void push(String input){
//check whether the stack is full
if (topOfStack+1< stackSize){
topOfStack++;
theStack[topOfStack]=input;
displayContent();
}else{
System.out.println("Stack is full!");
}
}
Here's the pop implementation:
public void pop(){
//if there is something to delete (=pop)
if (topOfStack>-1){
theStack[topOfStack]="-1";
displayContent();
}else{
System.out.println("Nothing to delete");
}
}
Queue
In Queues you can also only add (or also called "enqueue") a new item at the very end of the Array. But you can only delete (or also called "dequeue") the first item. This is called First-In-First-Out (FIFO).Here's the enqueue implementation:
public void enqueue(String input){
//if there's still place in the queue Array
if (queueLength< queueSize){
queueLength++;
String[] inputQ=new String[queueSize];
inputQ[0]=input;
String[] tempQ=new String[queueSize];
tempQ=theQueue;
//theQueue=ArrayUtils.addAll(inputQ, tempQ);
//merege
for (int j=1; j< queueSize; j++){
inputQ[j]=theQueue[j-1];
}
theQueue=inputQ;
displayQueue();
}else{
System.out.println("Queue is full");
}
}
Here's the dequeue implementation:
public void dequeue(){
//if there's still something in the queue
if (queueLength>0){
theQueue[queueLength]="-1";
queueLength--;
displayQueue();
}else{
System.out.println("Queue is empty");
}
}
You can see the complete JAVA program here on GitHub.
No comments:
Post a Comment