Data Structure Queue

class Node {
constructor(value){
this.value = value;
this.next = null;
}
}

class Queue {
constructor(){
this.first = null;
this.last = null;
this.size = 0;
}
  • This function accepts some value
  • Create a new Node using that value passed to the function
  • If there are no nodes in the queue, set this node to be the first and last property of the queue
  • Otherwise, set the next property on the current last to be that node, and then set the last property of the queue to be that node
  • If there is no first property, just return null
  • Store the first property in a variable
  • See if the first is the same as the last. If so, set the first and last to be null
  • If there are more than 1 node, set the first property to be the next property of first
  • Decrement the size by 1
  • Return the value of the node dequeued
class Node {
constructor(value){
this.value = value;
this.next = null;
}
}

class Queue {
constructor(){
this.first = null;
this.last = null;
this.size = 0;
}
enqueue(val){
var newNode = new Node(val)
if(!this.first){
this.first = newNode;
this.last = newNode;
} else {
this.last.next = newNode;
this.last = newNode;
}
return ++this.size;

}
dequeue(){
if(!this.first) return null;
var temp = this.first;
if(this.first === this.last){
this.last = null;

}
this.first = this.first.next
this.size --
return temp.value;
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Soner Mezgitci

Soner Mezgitci

31 Followers

Software Engineer | Ruby on Rails | JavaScript | HTML5 | CSS | PostgreSQL | React | Redux