Created
March 10, 2018 19:32
-
-
Save vadimkorr/9a762ede573fce2f42f53c41963d430f to your computer and use it in GitHub Desktop.
Implement Stack interface using 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
| // linked-list-as-stack | |
| function stack() { | |
| this.head = null; | |
| } | |
| stack.prototype.print = function() { | |
| let curr = this.head | |
| while(curr) { | |
| console.log(curr.val) | |
| curr = curr.next | |
| } | |
| } | |
| stack.prototype.push = function(val) { | |
| if (!this.head) { | |
| this.head = { | |
| val: val, | |
| next: null | |
| } | |
| } else { | |
| let pushed = { | |
| val: val, | |
| next: this.head | |
| } | |
| this.head = pushed; | |
| } | |
| } | |
| stack.prototype.pull = function() { | |
| let pulled; | |
| if (!this.head) { | |
| pulled = null; | |
| } else { | |
| pulled = this.head; | |
| this.head = this.head.next; | |
| } | |
| return pulled; | |
| } | |
| let st = new stack(); | |
| st.push(5); | |
| st.push(4); | |
| st.push(3); | |
| st.push(2); | |
| st.push(1); | |
| st.print(); | |
| st.pull(); | |
| st.print(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment