Last active
August 24, 2019 16:16
-
-
Save rankitranjan/5ec3df82095f223a7cc9cdbfc68500aa to your computer and use it in GitHub Desktop.
stack using LinkedList / array
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
// using LinkedList | |
class Node { | |
constructor(value) { | |
this.value = value; | |
this.next = null; | |
}; | |
} | |
class Stack { | |
constructor() { | |
this.top = null; | |
this.bottom = null; | |
this.length = 0; | |
} | |
push(value) { | |
const newNode = new Node(value); | |
if (this.length === 0) { | |
this.top = newNode; | |
this.bottom = newNode; | |
} else { | |
let holdingPointer = this.top; | |
this.top = newNode; | |
this.top.next = holdingPointer; | |
} | |
this.length += 1; | |
return this; | |
}; | |
peek() { | |
return this.top; | |
} | |
pop() { | |
if (!this.top) { | |
return null; | |
} else { | |
const holdingPointer = this.top; | |
this.top = this.top.next; | |
this.length -=1; | |
return holdingPointer | |
} | |
// return this; | |
} | |
} | |
const stack = new Stack(); | |
stack.push('google'); | |
stack.push('google1'); | |
stack.peek(); | |
stack.pop(); | |
// using Array | |
class StackArray { | |
constructor() { | |
this.array = []; | |
} | |
peek() { | |
return this.array[this.array.length-1]; | |
} | |
push(value) { | |
return this.array.push(value); | |
}; | |
pop() { | |
return this.array.pop(); | |
}; | |
} | |
const stack = new StackArray(); | |
stack.push('google1'); | |
stack.push('google2'); | |
stack.push('google3'); | |
stack.peek(); | |
stack.pop(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment