From 420a95dff62e3fc798dbd97ea0bb89e6a62075d0 Mon Sep 17 00:00:00 2001 From: nahome Date: Sun, 10 Jun 2018 18:24:47 -0700 Subject: [PATCH] linked-lists --- .../03-linked-lists/linked_list.rb | 43 ++++++++++++++++++- 01-data-structures/03-linked-lists/node.rb | 3 +- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/01-data-structures/03-linked-lists/linked_list.rb b/01-data-structures/03-linked-lists/linked_list.rb index 5ee2a533..9db66678 100644 --- a/01-data-structures/03-linked-lists/linked_list.rb +++ b/01-data-structures/03-linked-lists/linked_list.rb @@ -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 \ No newline at end of file +end diff --git a/01-data-structures/03-linked-lists/node.rb b/01-data-structures/03-linked-lists/node.rb index 016acb90..4358f9f2 100644 --- a/01-data-structures/03-linked-lists/node.rb +++ b/01-data-structures/03-linked-lists/node.rb @@ -3,5 +3,6 @@ class Node attr_accessor :data def initialize(data) + @data = data end -end \ No newline at end of file +end