Created
August 14, 2015 14:21
-
-
Save jimod/a3e420248a46309a8f84 to your computer and use it in GitHub Desktop.
Implementation of a string queue in java for tutorial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Queue { | |
private Node head; | |
private Node tail; | |
private int size; | |
public Queue(){ | |
head = null; | |
tail = null; | |
size = 0; | |
} | |
private class Node{ | |
private String item; | |
private Node next; | |
} | |
public boolean isEmpty(){ | |
if(head == null){ //if(this.size == 0) | |
return true; | |
} | |
else { | |
return false; | |
} | |
} | |
public void enq(String t){ | |
//check if queue is empty | |
if(isEmpty()){ //or if(this.head == null) | |
//add on a node with the string as an item | |
head.item = t; | |
//current item.next = null | |
head.next = null; | |
//increment the number of items in the queue | |
size++; | |
//set the node tail node equal to head node | |
tail = head; | |
} | |
else {//if its not empty | |
//create a new node to temp store tail | |
Node oldTail = tail; | |
Node newNode = new Node(); | |
// Put the item in the new tail | |
newNode.item = t; | |
//set current node.next to null | |
newNode.next = null; | |
//set oldTail.next to current node | |
oldTail.next = newNode; | |
tail = newNode; | |
} | |
} | |
public String toString(){ | |
//Instantiate a string to store all the concatenated strings | |
String allItems = ""; | |
//Iterate through the queue from head node to tail node | |
Node currentNode = head; | |
while(currentNode.next != null){ | |
//Concanenate current string to the overall string | |
allItems = allItems + " " +currentNode.item; | |
currentNode = currentNode.next; | |
} | |
return allItems; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment