Advertisement
Guest User

Untitled

a guest
Dec 15th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class List {
  2.     constructor() {
  3.         this.list = null
  4.     }
  5.  
  6.     push(v) {
  7.         if (this.list == null) {
  8.             this.list = () => {
  9.                 this.list = null
  10.                 return v
  11.             }
  12.         } else {
  13.             let temp = this.list
  14.  
  15.             this.list = () => {
  16.                 this.list = temp
  17.  
  18.                 return v
  19.             }
  20.         }
  21.     }
  22.  
  23.     pop() {
  24.         if (this.list == null) {
  25.             throw new Error('empty')
  26.         }
  27.  
  28.         return this.list()
  29.     }
  30.  
  31.     length() {
  32.         let count = 0
  33.         let temp = new List()
  34.  
  35.         while (this.list != null) {
  36.             temp.push(this.pop())
  37.  
  38.             count++
  39.         }
  40.  
  41.         while (temp.list != null) {
  42.             this.push(temp.pop())
  43.         }
  44.  
  45.         return count
  46.     }
  47.  
  48.     nth(n) {
  49.         let temp = new List()
  50.         let len = this.length()
  51.         let idx = len - n
  52.  
  53.         while (idx > 1) {
  54.             idx--
  55.  
  56.             temp.push(this.pop())
  57.         }
  58.  
  59.         let retVal = this.pop()
  60.         temp.push(retVal)
  61.  
  62.  
  63.         idx = len - n
  64.  
  65.  
  66.         while (idx > 0) {
  67.             idx--
  68.  
  69.             this.push(temp.pop())
  70.         }
  71.  
  72.         return retVal
  73.     }
  74. }
  75.  
  76. let l = new List()
  77.  
  78. l.push('hello')
  79. l.push(10)
  80. l.push(20)
  81. l.push(30)
  82. l.push('bye')
  83.  
  84. console.log(l.length())
  85.  
  86. console.log(l.nth(1))
  87.  
  88. console.log(l.pop())
  89. console.log(l.pop())
  90. console.log(l.pop())
  91. console.log(l.pop())
  92. console.log(l.pop())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement