PageRenderTime 27ms CodeModel.GetById 18ms app.highlight 6ms RepoModel.GetById 2ms app.codeStats 0ms

/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.
  2class LinkedList
  3
  4  constructor: ->
  5    @_head = null # Pointer to the first item in the list.
  6
  7
  8  # Appends some data to the end of the list. This method traverses the existing
  9  # list and places the value at the end in a new node.
 10  add: (data) ->
 11
 12    # Create a new node object to wrap the data.
 13    node = data: data, next: null
 14
 15    current = @_head or= node
 16
 17    if @_head isnt node
 18      current = current.next while current.next
 19      current.next = node
 20
 21    this
 22
 23
 24  # Retrieves the data at the given position in the list.
 25  item: (index) ->
 26
 27    # Check for out-of-bounds values.
 28    return null if index < 0
 29
 30    current = @_head or null
 31    i = -1
 32
 33    # Advance through the list.
 34    current = current.next while current and index > ++i
 35
 36    # Return null if we've reached the end.
 37    current and current.data
 38
 39
 40  # Remove the item from the given location in the list.
 41  remove: (index) ->
 42
 43    # Check for out-of-bounds values.
 44    return null if index < 0
 45
 46    current = @_head or null
 47    i = -1
 48
 49    # Special case: removing the first item.
 50    if index is 0
 51      @_head = current.next
 52    else
 53
 54      # Find the right location.
 55      [previous, current] = [current, current.next] while index > ++i
 56
 57      # Skip over the item to remove.
 58      previous.next = current.next
 59
 60    # Return the value.
 61    current and current.data
 62
 63
 64  # Calculate the number of items in the list.
 65  size: ->
 66    current = @_head
 67    count = 0
 68
 69    while current
 70      count += 1
 71      current = current.next
 72
 73    count
 74
 75
 76  # Convert the list into an array.
 77  toArray: ->
 78    result  = []
 79    current = @_head
 80
 81    while current
 82      result.push current.data
 83      current = current.next
 84
 85    result
 86
 87
 88  # The string representation of the linked list.
 89  toString: -> @toArray().toString()
 90
 91
 92# Tests.
 93list = new LinkedList
 94
 95list.add("Hi")
 96console.log list.size()  is 1
 97console.log list.item(0) is "Hi"
 98console.log list.item(1) is null
 99
100list = new LinkedList
101list.add("zero").add("one").add("two")
102console.log list.size()     is 3
103console.log list.item(2)    is "two"
104console.log list.remove(1)  is "one"
105console.log list.item(0)    is "zero"
106console.log list.item(1)    is "two"
107console.log list.size()     is 2
108console.log list.item(-10)  is null