Created
October 13, 2017 16:39
-
-
Save catmando/6cb6ad19824c2263699dce3dc385db0a to your computer and use it in GitHub Desktop.
Translate this code please
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 Node | |
# each node has a val (value) and a link to the next node. | |
def val # reads the instance variable val | |
@val | |
end | |
def next_node # reads the instance variable next_node | |
@next_node | |
end | |
def initialize(val, next_node) | |
@val = val | |
@next = next_node | |
end | |
end | |
class LinkedList | |
# for example we might say LinkedList.new(12) which would create a list with one element '12' in it. | |
def initialize(val) | |
@head = Node.new(val, nil) | |
end | |
# add another value (val) to end of list | |
# for example | |
# l = LinkedList.new(12) | |
# l.add(13) | |
# now l has two elements 12, and 13. | |
def add(val) | |
# start at the beginning | |
current = @head | |
# look for the end of the list | |
while current.next != nil | |
current = current.next | |
end | |
# shove a new node at the end of the list | |
current.next = Node.new(val, nil) | |
end | |
def delete(val) | |
# start at the beginning | |
current = @head | |
# check the special case that the first node is the one we are searching for | |
if current.val = val | |
@head = current.next | |
else | |
# otherwise search until we find the node we are looking for | |
while (current.next != nil) && (current.next.val != val) | |
current = current.next | |
end | |
# and if we find it, delete it. | |
unless current.next == nil | |
current.next = current.next.next | |
end | |
end | |
end | |
# turn the list into an array | |
def return_list | |
elements = [] | |
current = @head | |
while current.next != nil | |
elements << current | |
current = current.next | |
end | |
elements << current | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment