Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class List {
- constructor() {
- this.list = null
- }
- push(v) {
- if (this.list == null) {
- this.list = () => {
- this.list = null
- return v
- }
- } else {
- let temp = this.list
- this.list = () => {
- this.list = temp
- return v
- }
- }
- }
- pop() {
- if (this.list == null) {
- throw new Error('empty')
- }
- return this.list()
- }
- length() {
- let count = 0
- let temp = new List()
- while (this.list != null) {
- temp.push(this.pop())
- count++
- }
- while (temp.list != null) {
- this.push(temp.pop())
- }
- return count
- }
- nth(n) {
- let temp = new List()
- let len = this.length()
- let idx = len - n
- while (idx > 1) {
- idx--
- temp.push(this.pop())
- }
- let retVal = this.pop()
- temp.push(retVal)
- idx = len - n
- while (idx > 0) {
- idx--
- this.push(temp.pop())
- }
- return retVal
- }
- }
- let l = new List()
- l.push('hello')
- l.push(10)
- l.push(20)
- l.push(30)
- l.push('bye')
- console.log(l.length())
- console.log(l.nth(1))
- console.log(l.pop())
- console.log(l.pop())
- console.log(l.pop())
- console.log(l.pop())
- console.log(l.pop())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement