list.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * Simple doubly linked list implementation derived from Cormen, et al.,
  3. * "Introduction to Algorithms".
  4. */
  5. function List () {
  6. const sentinel = {}
  7. sentinel._next = sentinel._prev = sentinel
  8. this._sentinel = sentinel
  9. }
  10. List.prototype.dequeue = function () {
  11. const sentinel = this._sentinel
  12. const entry = sentinel._prev
  13. if (entry !== sentinel) {
  14. unlink(entry)
  15. return entry
  16. }
  17. }
  18. List.prototype.enqueue = function (entry) {
  19. const sentinel = this._sentinel
  20. if (entry._prev && entry._next) {
  21. unlink(entry)
  22. }
  23. entry._next = sentinel._next
  24. sentinel._next._prev = entry
  25. sentinel._next = entry
  26. entry._prev = sentinel
  27. }
  28. List.prototype.toString = function () {
  29. const strs = []
  30. const sentinel = this._sentinel
  31. let curr = sentinel._prev
  32. while (curr !== sentinel) {
  33. strs.push(JSON.stringify(curr, filterOutLinks))
  34. curr = curr._prev
  35. }
  36. return '[' + strs.join(', ') + ']'
  37. }
  38. function unlink (entry) {
  39. entry._prev._next = entry._next
  40. entry._next._prev = entry._prev
  41. delete entry._next
  42. delete entry._prev
  43. }
  44. function filterOutLinks (k, v) {
  45. if (k !== '_next' && k !== '_prev') {
  46. return v
  47. }
  48. }
  49. export default List