Guest User

Untitled

a guest
May 23rd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. class Node {
  2. constructor(value){
  3. this.value = value
  4. this.next = null
  5. }
  6. setNext(next){
  7. this.next = next
  8. }
  9. getNext(){
  10. return this.next
  11. }
  12. }
  13.  
  14. class LinkedList {
  15. constructor(){
  16. this.length = 0
  17. this.head = null
  18. this.tail = null
  19. }
  20.  
  21. push(value){
  22. const newNode = new Node(value)
  23.  
  24. if(this.length === 0) {
  25. this.head = this.tail = newNode
  26. }
  27. else {
  28. this.tail.setNext(newNode)
  29. this.tail = newNode
  30. }
  31.  
  32. this.length++
  33. }
  34.  
  35. pop(){
  36. if(this.length === 0) { return null }
  37. else {
  38. const oldTail = this.tail
  39. this.tail = this._findByIndex(this.length-2)
  40. this.tail.setNext(null)
  41. this.length--
  42. if(this.length === 0) { this.head = null }
  43. return oldTail.value
  44. }
  45. }
  46.  
  47. get(index){
  48. return this._findByIndex(index).value
  49. }
  50.  
  51. delete(index){
  52. let deletedNode
  53. if(index === 0) {
  54. deletedNode = this.head
  55. this.head = this.head.getNext()
  56. }
  57. else {
  58. const preNode = this._findByIndex(index-1)
  59. deletedNode = preNode.getNext()
  60. preNode.setNext(deletedNode.getNext())
  61. }
  62. this.length--
  63. return deletedNode.value
  64. }
  65.  
  66. _findByIndex(index){
  67. let currentNode = this.head,
  68. counter = 0,
  69. max = this.length
  70.  
  71. while (counter < max) {
  72. if(counter === index){
  73. return currentNode
  74. }
  75. currentNode = currentNode.getNext()
  76. counter++
  77. }
  78. }
  79.  
  80. _findByNext(findNextNode){
  81. let currentNode = this.head
  82. while (currentNode.getNext() !== null) {
  83. currentNode = currentNode.getNext()
  84. if(currentNode.getNext() === findNextNode){
  85. return currentNode
  86. }
  87. }
  88. }
  89. }
Add Comment
Please, Sign In to add comment