双向链表与普通链表的区别在于,在链表中,一个节点只有链向下一个节点的链接,而双向链表中,链接是双向的:一个链向下一个元素,另一个链向前一个元素:

    双向链表的实现 - 图1

    1. class Node {
    2. constructor(element) {
    3. this.element = element
    4. this.next = null // 保存前一个元素的引用
    5. this.prev = null // 保存后一个元素的引用
    6. }
    7. }
    8. class DoublyLinkedList {
    9. constructor() {
    10. this.length = 0 // 列表的元素个数
    11. this.head = null // 保存列表的第一项
    12. this.tail = null // 保存列表的最后一项
    13. }
    14. /**
    15. * 往指定位置插入元素
    16. * @param {number} position
    17. * @param {any} element
    18. */
    19. insert(position, element) {
    20. // 检查越界值,position 在 0 到 this.length 的范围为有效值
    21. if (position < 0 || position > this.length) {
    22. return false // 表示插入元素失败
    23. }
    24. let node = new Node(element)
    25. if (position === 0) {
    26. // 往列表第一个位置插入元素
    27. if (this.length === 0) {
    28. // 往空列表中插入元素,则列表的头部和尾部均指向同一个元素
    29. this.head = node
    30. this.tail = node
    31. } else {
    32. // 往非空列表中插入元素
    33. let oldHead = this.head
    34. node.next = oldHead
    35. oldHead.prev = node
    36. this.head = node
    37. }
    38. } else if (position === this.length) {
    39. // 往列表末尾添加元素
    40. let oldTail = this.tail
    41. oldTail.next = node
    42. node.prev = oldTail
    43. this.tail = node
    44. } else {
    45. // 从列表中间插入元素
    46. let previous = this.head
    47. let current = this.head.next
    48. for (let i = 1; i < this.length; i++) {
    49. previous = current
    50. current = current.next
    51. }
    52. previous.next = node
    53. current.prev = node
    54. node.prev = previous
    55. node.next = current
    56. }
    57. this.length++
    58. return true
    59. }
    60. /**
    61. * 从指定位置删除元素
    62. * @param {number} position
    63. */
    64. removeAt(position) {
    65. // 检查越界值
    66. if (position < 0 || position >= this.length) {
    67. return null
    68. }
    69. let result
    70. if (position === 0) {
    71. // 删除第一个位置的元素
    72. result = this.head
    73. if (this.length === 1) {
    74. // 原来的列表中仅有一个元素
    75. this.head = null
    76. this.tail = null
    77. } else {
    78. let oldHead = this.head
    79. // 将 this.head 改变 this.head 的下一个元素
    80. this.head = oldHead.next
    81. this.head.prev = null
    82. }
    83. } else if (position === this.length - 1) {
    84. // 删除的是最后一个位置的元素
    85. let oldTail = result = this.tail
    86. this.tail = oldTail.prev
    87. this.tail.next = null
    88. } else {
    89. let current = this.head
    90. let previous = null
    91. for(let i = 1; i <= position ; i++) {
    92. previous = current
    93. current = current.next
    94. }
    95. result = current
    96. previous.next = current.next
    97. current.next.prev = previous
    98. }
    99. this.length--
    100. return result.element
    101. }
    102. }