Advertisement
Guest User

Untitled

a guest
Apr 1st, 2015
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. Algorithm Night
  2. ===============
  3.  
  4. ####Linked Lists
  5. - reference based ds
  6. - a collection of node objects
  7. - each node possesses a value and a reference
  8.  
  9. _PRO:_ adding anywhere but the end is better
  10. _CON:_ adding at the end takes longer (have to find 'end')
  11.  
  12. - no bound capacity, fixed sized arrays aren't a problem anymore in other languages
  13. - basis for other data structures (e.g. trees, graphs)
  14.  
  15. - used on other data structures we discussed two weeks ago (stacks, queques)
  16.  
  17. #####Node Class:
  18. `````ruby
  19. class Node
  20. # contains value and a reference
  21. attr_accessor :value, :next
  22.  
  23.  
  24. def initialize value
  25. @value = value
  26. end
  27. end
  28.  
  29. first = Node.new(42)
  30. second = Node.new(-3)
  31. third = Node.new(17)
  32. fourth = Node.new(0)
  33.  
  34. first.next = second
  35. second.next = third
  36. third.next = fourths
  37. ```````
  38.  
  39. #####Linked List Class:
  40. `````ruby
  41.  
  42. # out linked list holds our nodes and allows us
  43. # to call us methods/functions on them
  44. class LinkedList
  45. attr_accessor :head, :size
  46.  
  47. # Initially there is no 'head' and the size of the list is 0
  48. def initialize
  49. @head = nil
  50. @size = 0
  51. end
  52.  
  53. def add_to_end value
  54. if @size == 0
  55.  
  56. @head = Node.new(value)
  57. @size += 1
  58. else
  59.  
  60. current = @head
  61. index = 0
  62. while index < @size
  63. current.next = Node.new(value) if current.next == nil
  64. current = current.next
  65. index += 1
  66. end
  67. @size += 1
  68. end
  69. end
  70.  
  71.  
  72. end
  73. `````````
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement