Last active
November 1, 2018 10:56
-
-
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.
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
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