Skip to content

Instantly share code, notes, and snippets.

@LordRahl90
Last active November 1, 2018 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LordRahl90/6facb262e8785a07c648fc602fd293a6 to your computer and use it in GitHub Desktop.
Save LordRahl90/6facb262e8785a07c648fc602fd293a6 to your computer and use it in GitHub Desktop.
My Attempt at implementing a queue based on my understanding of linked list in java. Will try to replicate this in golang soon enuf.
public class Queue{
private Node head;
private int length;
public void printQueue(){
Node n=this.head;
while(n!=null){
System.out.println(n.data+"");
n=n.next;
}
}
// To Implement a queue, Insertion has to occur at the back while removal should be at the front.
/**
* Items are added at the back of the queue.
* To Optimize this, we can keep track of the length of the queue.
* Then proceeed to insert at that element.
* But for the sake of this tutorial, we will iterate to the last value.
*/
public void push(int newItem){
Node n=head;
Node newNode=new Node(newItem);
if(head==null){
head=newNode;
return;
}
while(n.next!=null){
n=n.next;
}
this.length++;
n.next=newNode;
}
/**
* There is no need for parameter as only the first item can be removed.
* I may want to return the item being popped.
*/
public Node pop(){
Node formerHead=head;
head=head.next;
this.length--;
return formerHead;
}
public Node top(){
return this.head;
}
public int getLength(){
return this.length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment