Created
August 16, 2020 17:14
-
-
Save jasterix/110d0071fb71104ab5661b07ded5ba80 to your computer and use it in GitHub Desktop.
Implementing a stack with a singly linked list
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
class Node { | |
constructor(value){ | |
this.value = value; | |
this.next = null; | |
} | |
} | |
class Stack { | |
constructor(){ | |
this.first = null; | |
this.last = null; | |
this.size = 0; | |
} | |
push(val){ | |
var newNode = new Node(val); | |
if(!this.first){ | |
this.first = newNode; | |
this.last = newNode; | |
} else { | |
var temp = this.first; | |
this.first = newNode; | |
this.first.next = temp; | |
} | |
return ++this.size; | |
} | |
pop(){ | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment