Created
June 25, 2017 03:22
-
-
Save dakotabryant/f793b091796eb5c5b082848de7377641 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
//Creates a node containing the data and a reference to the next item | |
function createNode(data = null, next = null) { | |
return { | |
data, | |
next | |
}; | |
} | |
class Stack { | |
constructor() { | |
this.top = null; | |
} | |
push(data) { | |
//if the top of the stack is empty, then the data will be the | |
//top of the stack | |
if (this.top === null) { | |
this.top = createNode(data); | |
return; | |
} | |
//if the top already has something then create a new node | |
//add data to the new node | |
// have the pointer point to the top | |
const node = createNode(data, this.top); | |
this.top = node; | |
} | |
pop() { | |
//in order to remove the top of the stack, you have to point | |
//the pointer to the next item and that next item becomes the | |
//top of the stack | |
const node = this.top; | |
this.top = node.next; | |
return node.data; | |
} | |
} | |
let s = new Stack(); | |
s.push(1); | |
s.push(2); | |
s.push("Tauhida"); | |
//console.log("Top of stack:", peek(s)); | |
s.pop(); | |
s.push("joe"); | |
//console.log("Top of stack:", peek(s)); | |
display(); | |
function peek() { | |
//if the top of the stack does not have anything | |
//then the stack is empty | |
//otherwise return what's on the top | |
if (s.top === null) { | |
return null; | |
} | |
return s.top.data; | |
} | |
function display() { | |
// displays the entire contents of the stack | |
let node = s.top; | |
while (node !== null) { | |
//console.log(node.data); | |
node = node.next; | |
} | |
} | |
let balancedStack = new Stack(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment