Simple singly linked list written with Ruby

Linked list in Ruby is probably the easiest way to write linked list. In Ruby, everything is pass by reference. You will never use such thing as pointers in Ruby. Check out this Node class below.

class Node
  attr_accessor :value, :next

  def initialize(value)
    @value = value
  end
end

A node has two attributes, value and next. attr_accessor is a method that creates other methods. A getter and a setter are created for both value attribute and next attribute. initalize method is Ruby’s way of writing a constructor. So whenever there’s Node.new, initialize is called.

The rest are methods used to print the list in the forward direct and reverse direction.

def print_forward(node)
  while node != nil
    puts node.value
    node = node.next
  end
end

def reverse(node)
  first = node
  second = node.next
  current = node.next
  first.next = nil
  while second != nil
    second = second.next
    current.next = first
    first = current
    current = second    
  end
  first
end

def print_reverse(node)
  print_forward(reverse(node))
end

Here are some test code to try out.

c = Node.new('c')
b = Node.new('b')
a = Node.new('a')
a.next = b
b.next = c

# a -> b -> c

print_forward(a)
print_reverse(a)
print_reverse(c)
This was posted 9 months ago. It has 2 notes.
  1. briandear reblogged this from allfuzzy
  2. allfuzzy posted this