Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

linked-lists #145

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion 01-data-structures/03-linked-lists/linked_list.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,66 @@ class LinkedList

# This method creates a new `Node` using `data`, and inserts it at the end of the list.
def add_to_tail(node)
if @head = nil
self.head = node
self.tail = node
else
self.tail.next = node
self.node = node
end
end

# This method removes the last node in the lists and must keep the rest of the list intact.
def remove_tail
current = @head
while current.next.next != nil
current = current.next
end
@tail = current
@tail.next = nil
end

# This method prints out a representation of the list.
def print
current = self.head
puts current.data
until current = self.tail
current = current.next
puts current.data
end
end

# This method removes `node` from the list and must keep the rest of the list intact.
def delete(node)
if self.head == node
remove_front
elsif self.tail == node
remove_tail
else
current_node = self.head
until current_node.next == node
current_node = current_node.next
end
current_node.next = node.next
end
end

# This method adds `node` to the front of the list and must set the list's head to `node`.
def add_to_front(node)
unless self.head.nil?
node.next = self.head
else
self.head = node
end
end

# This method removes and returns the first node in the Linked List and must set Linked List's head to the second node.
def remove_front
unless self.head.next.nil?
self.head = self.head.next
else
self.head = nil
self.tail = nil
end
end
end
end
3 changes: 2 additions & 1 deletion 01-data-structures/03-linked-lists/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ class Node
attr_accessor :data

def initialize(data)
@data = data
end
end
end