Created
June 26, 2009 11:23
-
-
Save jroes/136424 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'test/unit' | |
require 'shoulda' | |
require 'pointers' | |
class ListNodeTest < Test::Unit::TestCase | |
context "A LinkedList instance" do | |
setup do | |
@list = LinkedList.new | |
@list.insert!('Not Boomshakalaka') | |
@list.insert!('still not it') | |
@list.insert!('definitely not') | |
end | |
context "containing Boomshakalaka" do | |
setup do | |
@list.insert!('Boomshakalaka') | |
end | |
should "contain Boomshakalaka" do | |
assert_equal true, @list.contains?('Boomshakalaka') | |
end | |
end | |
context "containing Boomshakalaka a few elements down" do | |
setup do | |
@list.insert!('Boomshakalaka') | |
@list.insert!('Always') | |
@list.insert!('Be') | |
@list.insert!('Coding') | |
end | |
should "contain Boomshakalaka" do | |
assert_equal true, @list.contains?('Boomshakalaka') | |
end | |
end | |
context "not containing Boomshakalaka" do | |
setup do | |
@list.insert!('dusty room') | |
@list.insert!('tumbleweed') | |
end | |
should "not contain Boomshakalaka" do | |
assert_equal false, @list.contains?('Boomshakalaka') | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ListNode < Object | |
attr_accessor :data, :next, :prev | |
end | |
class LinkedList | |
# Insert an item into the front of the list | |
def insert!(item) | |
node = ListNode.new | |
node.data = item | |
node.prev = nil | |
node.next = @head | |
@head.prev = node unless @head.nil? | |
@head = node | |
end | |
# Find given item in list | |
def contains?(item) | |
node = @head | |
while node | |
return true if node.data == item | |
node = node.next | |
end | |
return false | |
end | |
# Traverse list | |
def inspect | |
node = @head | |
trav = "" | |
while node | |
trav += " <- #{node.data} -> " | |
node = node.next | |
end | |
return trav | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment