Skip to content

Instantly share code, notes, and snippets.

@shtakai
Created May 16, 2016 21:29
Show Gist options
  • Save shtakai/993b13a6b6fe5ab32959ab481cf074a8 to your computer and use it in GitHub Desktop.
Save shtakai/993b13a6b6fe5ab32959ab481cf074a8 to your computer and use it in GitHub Desktop.
linked list(dirty)
require 'pp'
class LinkedList
attr_accessor :head
def initialize(head=nil)
@head = head
head
end
def add_to_head(node)
node.next = @head
@head = node
node
end
def add_to_tail(node)
last = traverse
last.next = node
node
end
def traverse
runner = @head
while(runner.next)
runner = runner.next
end
runner
end
def has_value(value)
runner = @head
while(runner.next)
if runner.value == value
pp "value found:#{value} on Node:#{runner}"
break
end
runner = runner.next
end
end
end
class Node
attr_accessor :next, :value
def initialize(value)
@value = value
@nxt = nil
end
end
node_1 = Node.new("node_1")
node_2 = Node.new("node_2")
node_3 = Node.new("node_3")
node_4 = Node.new("node_4")
node_5 = Node.new("node_5")
list = LinkedList.new(node_1)
list.add_to_head node_2
list.add_to_head node_3
list.add_to_head node_4
list.add_to_head node_5
node_6 = Node.new("node_6")
list.add_to_tail(node_6)
pp list
list.has_value("node_3")
@shtakai
Copy link
Author

shtakai commented May 16, 2016

➜ linkedlist git:(master) ✗ ruby ll.rb

<LinkedList:0x007fdf6c0f02c8

@Head=
#<Node:0x007fdf6c0f0318
@next=
#<Node:0x007fdf6c0f0368
@next=
#<Node:0x007fdf6c0f03e0
@next=
#<Node:0x007fdf6c0f0458
@next=
#<Node:0x007fdf6c0f04a8
@next=#<Node:0x007fdf6c0f0278 @NXT=nil, @value="node_6">,
@NXT=nil,
@value="node_1">,
@NXT=nil,
@value="node_2">,
@NXT=nil,
@value="node_3">,
@NXT=nil,
@value="node_4">,
@NXT=nil,
@value="node_5">>
"value found:node_3 on Node:#Node:0x007fdf6c0f03e0"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment