Last active
August 29, 2015 14:00
-
-
Save skharel/11119101 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
* | |
* This code is written for Queue tutorial | |
* The comment won't make sense unless you read the slide that goes with it | |
* | |
* Go to Vumari.com to find slides | |
* | |
*/ | |
public class LinkedListQueue { | |
private static class Node{ | |
int data; | |
Node next; | |
public Node(int data) { | |
this.data = data; | |
next = null; | |
} | |
} | |
private Node head, tail; | |
private int size = 0; | |
public void enequeue(int aData){ | |
Node aNewNode = new Node(aData); | |
if(head == null){//for the first time | |
head = aNewNode; | |
tail = aNewNode; | |
}else{ | |
//second & more times | |
tail.next = aNewNode; //previous node says hello to new guy | |
tail = aNewNode; //point to the new end; | |
} | |
size++; | |
} | |
public int dequeue(){ | |
if(isEmpty()){ | |
throw new NullPointerException("There is nothing to dequeue from this queue."); | |
} | |
int temp = head.data; | |
head = head.next; | |
size--; | |
return temp; | |
} | |
public boolean isEmpty(){ | |
//if any of the pointer head or tail is null, its empty | |
return head == null; | |
} | |
public int getSize(){ | |
return size; | |
} | |
@Override | |
public String toString() { | |
StringBuilder queueSnapshot = new StringBuilder(); | |
Node printerGuy = head; | |
while(printerGuy!=null){ //even if the head was null, we will get empty string but not any exception | |
queueSnapshot.append(printerGuy.data + ", "); | |
printerGuy = printerGuy.next; | |
} | |
return queueSnapshot.toString().replaceAll(", $", ""); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment