Advertisement
Guest User

Untitled

a guest
May 26th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. //the DoublyLinkedList class
  2. function DoublyLinkedList() {
  3. this.head = null
  4. this.tail = null
  5. this.length = 0
  6. }
  7.  
  8. //the Node class
  9. function Node(value) {
  10. this.value = value
  11. this.next = null
  12. this.previous = null
  13. }
  14.  
  15. DoublyLinkedList.prototype.find = function(value) {
  16. var currNode = this.head
  17. while(currNode.value != value){ // if value found exit while loop
  18. currNode = currNode.next
  19. }
  20. return currNode
  21. }
  22.  
  23. DoublyLinkedList.prototype.add = function(value) {
  24. var node = new Node(value)
  25.  
  26. if(!this.head) { //if list is empty
  27. this.head = this.tail = node // new node will be both head and tail
  28.  
  29. } else { //if not, new node becomes tail
  30. node.previous = this.tail //set previous of new node to be old tail
  31. this.tail.next = node //set next of old tail to be new node
  32. this.tail = node // set node to be the new tail
  33. }
  34. this.length++
  35. return node
  36. }
  37.  
  38. DoublyLinkedList.prototype.remove = function(value) {
  39.  
  40. var currNode = this.find(value) // node to be deleted
  41.  
  42. if(currNode === this.head && currNode === this.tail) { //only one node?
  43. this.head = null
  44. this.tail = null
  45. } else if(currNode === this.head) { //if node to be removed is head
  46. this.head = currNode.next //assign a new head
  47. currNode.previous = null
  48. } else if(currNode === this.tail) { //if node to be removed is tail
  49. this.tail = currNode.previous //assign a new tail
  50. currNode.next = null
  51. } else { //if regular node, rewire next and previous to skip removed node
  52. currNode.previous.next = currNode.next
  53. currNode.next.previous = currNode.previous
  54. }
  55. this.length--
  56. }
  57.  
  58. DoublyLinkedList.prototype.print = function(){
  59. var list = ''
  60. var currNode = this.head
  61. while(currNode) {
  62. list += currNode.value + ' '
  63. currNode = currNode.next
  64. }
  65. console.log(list)
  66. }
  67.  
  68. //DoublyLinkedList test
  69. var l = new DoublyLinkedList()
  70. l.add('1')
  71. l.add('2')
  72. l.add('3')
  73. l.add('4')
  74. l.print() //1 2 3 4
  75. l.tail.value //4
  76. l.tail.previous.value //3
  77. l.remove('3')
  78. l.print() //1 2 4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement