/examples/computer_science/linked_list.coffee

http://github.com/jashkenas/coffee-script · CoffeeScript · 108 lines · 55 code · 35 blank · 18 comment · 9 complexity · cec5c68e3ecc984021deedd979ef3e7d MD5 · raw file

  1. # "Classic" linked list implementation that doesn't keep track of its size.
  2. class LinkedList
  3. constructor: ->
  4. @_head = null # Pointer to the first item in the list.
  5. # Appends some data to the end of the list. This method traverses the existing
  6. # list and places the value at the end in a new node.
  7. add: (data) ->
  8. # Create a new node object to wrap the data.
  9. node = data: data, next: null
  10. current = @_head or= node
  11. if @_head isnt node
  12. current = current.next while current.next
  13. current.next = node
  14. this
  15. # Retrieves the data at the given position in the list.
  16. item: (index) ->
  17. # Check for out-of-bounds values.
  18. return null if index < 0
  19. current = @_head or null
  20. i = -1
  21. # Advance through the list.
  22. current = current.next while current and index > ++i
  23. # Return null if we've reached the end.
  24. current and current.data
  25. # Remove the item from the given location in the list.
  26. remove: (index) ->
  27. # Check for out-of-bounds values.
  28. return null if index < 0
  29. current = @_head or null
  30. i = -1
  31. # Special case: removing the first item.
  32. if index is 0
  33. @_head = current.next
  34. else
  35. # Find the right location.
  36. [previous, current] = [current, current.next] while index > ++i
  37. # Skip over the item to remove.
  38. previous.next = current.next
  39. # Return the value.
  40. current and current.data
  41. # Calculate the number of items in the list.
  42. size: ->
  43. current = @_head
  44. count = 0
  45. while current
  46. count += 1
  47. current = current.next
  48. count
  49. # Convert the list into an array.
  50. toArray: ->
  51. result = []
  52. current = @_head
  53. while current
  54. result.push current.data
  55. current = current.next
  56. result
  57. # The string representation of the linked list.
  58. toString: -> @toArray().toString()
  59. # Tests.
  60. list = new LinkedList
  61. list.add("Hi")
  62. console.log list.size() is 1
  63. console.log list.item(0) is "Hi"
  64. console.log list.item(1) is null
  65. list = new LinkedList
  66. list.add("zero").add("one").add("two")
  67. console.log list.size() is 3
  68. console.log list.item(2) is "two"
  69. console.log list.remove(1) is "one"
  70. console.log list.item(0) is "zero"
  71. console.log list.item(1) is "two"
  72. console.log list.size() is 2
  73. console.log list.item(-10) is null