From 283c91cf748494f381c811926da9ef3025cf2a28 Mon Sep 17 00:00:00 2001 From: Cyndi Lopez Date: Fri, 30 Aug 2019 22:09:22 -0700 Subject: [PATCH] completed the exercises and added a few more linked lists problems performed as part of CS class @ Uber --- .DS_Store | Bin 0 -> 8196 bytes lib/example.rb | 62 +++++ lib/linked_list.rb | 390 +++++++++++++++++++++++--------- test/linked_list_test.rb | 475 ++++++++++++++++++++------------------- 4 files changed, 587 insertions(+), 340 deletions(-) create mode 100644 .DS_Store create mode 100644 lib/example.rb diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..0f61d6c6c984595ff647f50603db852e970b5122 GIT binary patch literal 8196 zcmeHLO>h)N6n-xWVP+ttK?oUOldY^#z(9ToELi+(vcV!nl*s0nfXnR8NJb|!ac4FQ ziNREP5eq$71s0qvy-0De#L^QNF9-)cU`o&`4<0<|#iOOARle??Fak0I<7gwgc1yfI<(KY#C(_NnFpL2U11YQbiKUANyTb=gYz_4AbAe?Q}B9o)TwrhH&Zm;N?zUU_-6=I+) ztDl+aOm1t5w{P#5ZHdn$lWi^W9m$=uv#PSTxqVOX@rhH@Gq2B{z91vQ@T&l|3nILD zH$2CmO3UksiuZDpGQ8V&!qb-N2YR)GBX-_%GxoHVWwky<*Gtv@f;B~v4Cg(kIN|zP zwlZ%x`J!V4R+r;&V}B&DP6oVm#PZeYJ`TZO@rZ3g3`hM%`w({@h` zPuaembF2Z^n6Or2i>l7ot*x)o*XbL|s)a5JODH47oc&tS4o-tkG#E?AVCiZahu)YfPl_01|XlmVaOl`UJeR+ahcz^k;VqDAk}Iu&NB zgN~829NCoAb}8(jIy@!AmW`{lJ&HP#_a-JNNM8)QFQw}*@nQQ6KR7gLxiqEgG7xx5AYNG6tCcCconbVS9l$7;7z=Rx8*D=$~^6p^>U6sP$_&3 ziKpQ;TE*zYcpBUPoRqnIM+# zJ_>Rg>+9BQu|Xn~b#ftz%j9NDIq8*ootP1e$C?!42@9*uv8NScGOG}MZQ2~uSS68G zydnD5RxQSs5I+^6-PWmTtcnOMwL5o_wwkCayVBNc`&5;I7)EQ3rB#LDLgFn-yGw8d zzJ#ygCeiIj_!)kM-w}vv%dw8A7RLlWiOskbTd^HGuoL&--jH;C_yYFhi$uIJJce03 zjt0Jh4$;oTNjycgo5j=k2EK)7@NFXCIXq7Uynq++Bm8&)-42wACM90FOSh>^!F4?M z1htgOdB1T~dsGpql!4Xr^Z)+E@Bbgw@T0gQ1R?|o0j%oD^mOyWB5?4tcATE$^zg*( z=A;xZl-+j`K=trAE^Omu%6(FyoRd^`7d1r(62?b|I-SDznjti&)N9+rGEfB C%+iJc literal 0 HcmV?d00001 diff --git a/lib/example.rb b/lib/example.rb new file mode 100644 index 00000000..93a8b4c7 --- /dev/null +++ b/lib/example.rb @@ -0,0 +1,62 @@ +class LinkedList + def initialize + @head = nil + end + + def append(value) + if @head + find_tail.next = Node.new(value) + else + @head = Node.new(value) + end + end + + def find_tail + node = @head + return node if !node.next + return node if !node.next while (node = node.next) + end + + def append_after(target, value) + node = find(target) + return unless node + old_next = node.next + node.next = Node.new(value) + node.next.next = old_next + end + + def find(value) + node = @head + return false if !node.next + return node if node.value == value + while (node = node.next) + return node if node.value == value + end + end + + def delete(value) + if @head.value == value + @head = @head.next + return + end + node = find_before(value) + node.next = node.next.next + end + + def find_before(value) + node = @head + return false if !node.next + return node if node.next.value == value + while (node = node.next) + return node if node.next && node.next.value == value + end + end + + def print + node = @head + puts node + while (node = node.next) + puts node + end + end +end diff --git a/lib/linked_list.rb b/lib/linked_list.rb index 501c60fb..685ca11d 100644 --- a/lib/linked_list.rb +++ b/lib/linked_list.rb @@ -12,152 +12,320 @@ def initialize(value, next_node = nil) # Defines the singly linked list class LinkedList - def initialize - @head = nil # keep the head private. Not accessible outside this class - end + def initialize + @head = nil # keep the head private. Not accessible outside this class + end - # method to add a new node with the specific data value in the linked list - # insert the new node at the beginning of the linked list - # Time Complexity: - # Space Complexity - def add_first(value) - raise NotImplementedError - end + # method to add a new node with the specific data value in the linked list + # insert the new node at the beginning of the linked list + # Time Complexity: O(1) + # Space Complexity: O(1) + def add_first(value) + @head = Node.new(value, @head) + return + end - # method to find if the linked list contains a node with specified value - # returns true if found, false otherwise - # Time Complexity: - # Space Complexity - def search(value) - raise NotImplementedError + # method to find if the linked list contains a node with specified value + # returns true if found, false otherwise + # Time Complexity: O(n) + # Space Complexity: O(1) + def search(value) + current_node = @head + while !current_node.nil? + if current_node.data == value + return true + end + current_node = current_node.next end + return false + end - # method to return the max value in the linked list - # returns the data value and not the node - # Time Complexity: - # Space Complexity - def find_max - raise NotImplementedError + # method to return the max value in the linked list + # returns the data value and not the node + # Time Complexity: O(n) + # Space Complexity: O(1) + def find_max + current_node = @head + return nil if current_node.nil? + max_value = current_node.data + while !current_node.next.nil? + if current_node.next.data > max_value + max_value = current_node.next.data + end + current_node = current_node.next end + return max_value + end - # method to return the min value in the linked list - # returns the data value and not the node - # Time Complexity: - # Space Complexity - def find_min - raise NotImplementedError + # method to return the min value in the linked list + # returns the data value and not the node + # Time Complexity: O(n) + # Space Complexity: O(1) + def find_min + current_node = @head + return nil if current_node.nil? + min_value = current_node.data + while !current_node.next.nil? + if current_node.next.data < min_value + min_value = current_node.next.data + end + current_node = current_node.next end + return min_value + end - - # method that returns the length of the singly linked list - # Time Complexity: - # Space Complexity - def length - raise NotImplementedError + # method that returns the length of the singly linked list + # Time Complexity: O(n) + # Space Complexity: O(1) + def length + current = @head + return 0 if current.nil? + count = 0 + while current != nil + count += 1 + current = current.next end + return count + end - # method that returns the value at a given index in the linked list - # index count starts at 0 - # returns nil if there are fewer nodes in the linked list than the index value - # Time Complexity: - # Space Complexity - def get_at_index(index) - raise NotImplementedError + # method that returns the value at a given index in the linked list + # index count starts at 0 + # returns nil if there are fewer nodes in the linked list than the index value + # Time Complexity: O(n) + # Space Complexity: O(1) + def get_at_index(index) + current = @head + count = 0 + while !current.nil? + if index == count + return current.data + end + count += 1 + current = current.next end + return current.data if index == count + return nil + end - # method to print all the values in the linked list - # Time Complexity: - # Space Complexity - def visit - raise NotImplementedError + # method to print all the values in the linked list + # Time Complexity: O(n) + # Space Complexity O(1) + def visit + return nil if @head.nil? + current = @head + while !current.nil? + puts(current.data) + current = current.next end + end - # method to delete the first node found with specified value - # Time Complexity: - # Space Complexity - def delete(value) - raise NotImplementedError + # method to delete the first node found with specified value + # Time Complexity: O(n) + # Space Complexity: O(1) + def delete(value) + return if @head.nil? + if @head.data == value + @head = @head.next + return end - - # method to reverse the singly linked list - # note: the nodes should be moved and not just the values in the nodes - # Time Complexity: - # Space Complexity - def reverse - raise NotImplementedError + current = @head + while !current.next.nil? + if current.next.data == value + current.next = current.next.next + return + end + current = current.next end + return + end + # method to reverse the singly linked list + # note: the nodes should be moved and not just the values in the nodes + # Time Complexity: O(n) + # Space Complexity O(1) + def reverse + current_node = @head + prev_node = nil + next_node = nil + while !current_node.nil? + next_node = current_node.next + current_node.next = prev_node + prev_node = current_node + current_node = next_node + end + @head = prev_node + end - ## Advanced Exercises - # returns the value at the middle element in the singly linked list - # Time Complexity: - # Space Complexity - def find_middle_value - raise NotImplementedError + ## Advanced Exercises + # returns the value at the middle element in the singly linked list + # Time Complexity: O(n) + # Space Complexity: O(1) + def find_middle_value + return nil if @head.nil? + current = @head + len = self.length + return @head if len == 1 + mid_val = len / 2 + count = 1 + while count <= len + if count == mid_val + return current.data + end + current = current.next + count += 1 end + end - # find the nth node from the end and return its value - # assume indexing starts at 0 while counting to n - # Time Complexity: - # Space Complexity - def find_nth_from_end(n) - raise NotImplementedError + # find the nth node from the end and return its value + # assume indexing starts at 0 while counting to n + # Time Complexity:O(n) + # Space Complexity:O(1) + def find_nth_from_end(n) + current = @head + len = self.length + count = len - 1 + return if n > count + current = @head + while !current.nil? + if count == n + return current.data + end + current = current.next + count -= 1 end + end - # checks if the linked list has a cycle. A cycle exists if any node in the - # linked list links to a node already visited. - # returns true if a cycle is found, false otherwise. - # Time Complexity: - # Space Complexity - def has_cycle - raise NotImplementedError + # checks if the linked list has a cycle. A cycle exists if any node in the + # linked list links to a node already visited. + # returns true if a cycle is found, false otherwise. + # Time Complexity: O(n) + # Space Complexity: O(n) + def has_cycle + visited_nodes = [] + current = @head + while !current.nil? + if visited_nodes.include?(current) + return true + end + visited_nodes.append(current) + current = current.next end + return false + end + # Additional Exercises + # returns the value in the first node + # returns nil if the list is empty + # Time Complexity: O(1) + # Space Complexity: O(1) + def get_first + node = @head + return nil if node.nil? + return node.data + end - # Additional Exercises - # returns the value in the first node - # returns nil if the list is empty - # Time Complexity: - # Space Complexity - def get_first - raise NotImplementedError + # method that inserts a given value as a new last node in the linked list + # Time Complexity: O(n) + # Space Complexity: O(1) + def add_last(value) + if @head.nil? + add_first(value) + return end + current = @head + while !current.next.nil? + current = current.next + end + last_value = Node.new(value) + current.next = last_value + end - # method that inserts a given value as a new last node in the linked list - # Time Complexity: - # Space Complexity - def add_last(value) - raise NotImplementedError + # method that returns the value of the last node in the linked list + # returns nil if the linked list is empty + # Time Complexity: O(n) + # Space Complexity: O(1) + def get_last + return nil if @head.nil? + current = @head + while !current.next.nil? + current = current.next end + return current.data + end - # method that returns the value of the last node in the linked list - # returns nil if the linked list is empty - # Time Complexity: - # Space Complexity - def get_last - raise NotImplementedError + # method to insert a new node with specific data value, assuming the linked + # list is sorted in ascending order + # Time Complexity: O(n) + # Space Complexity: O(1) + def insert_ascending(value) + if @head.nil? + self.add_first(value) + return + end + current = @head + while !current.nil? + if current.next.data >= value + current.next = current.next.next + return + end + current = current.next end + self.add_last(value) + return + end - # method to insert a new node with specific data value, assuming the linked - # list is sorted in ascending order - # Time Complexity: - # Space Complexity - def insert_ascending(value) - raise NotImplementedError + def remove_duplicates + current = @head + values = [] + while !current.nil? + if values.include?(current.data) + current.next = current.next.next + return + end + values.append(current) + current = current.next end + end - # Helper method for tests - # Creates a cycle in the linked list for testing purposes - # Assumes the linked list has at least one node - def create_cycle - return if @head == nil # don't do anything if the linked list is empty + def get_head + node = @head + return nil if node.nil? + return node + end - # navigate to last node - current = @head - while current.next != nil - current = current.next + def partition(value) + smaller = LinkedList.new + greater = LinkedList.new + current = @head + while !current.nil? + if current.data < value + smaller.add_last(current.data) + else + greater.add_last(current.data) end + current = current.next + end + head2 = smaller.get_head + while !head2.next.nil? + head2 = head2.next + end + head2.next = greater.get_head + puts(head2.next.data) + return smaller + end + + # Helper method for tests + # Creates a cycle in the linked list for testing purposes + # Assumes the linked list has at least one node + def create_cycle + return if @head == nil # don't do anything if the linked list is empty - current.next = @head # make the last node link to first node + # navigate to last node + current = @head + while current.next != nil + current = current.next end + + current.next = @head # make the last node link to first node + end end diff --git a/test/linked_list_test.rb b/test/linked_list_test.rb index 8311c439..010a277e 100644 --- a/test/linked_list_test.rb +++ b/test/linked_list_test.rb @@ -1,236 +1,253 @@ -require 'minitest/autorun' -require 'minitest/reporters' -require 'minitest/skip_dsl' - -require_relative 'test_helper' +require "minitest/autorun" +require "minitest/reporters" +require "minitest/skip_dsl" +require_relative "test_helper" Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new describe LinkedList do - # Arrange - before do - @list = LinkedList.new - end - - describe 'initialize' do - it 'can be created' do - - # Assert - expect(@list).must_be_kind_of LinkedList - end - end - - describe 'add_first & get_first' do - it 'can add values to an empty list' do - # Act - @list.add_first(3) - - # Assert - expect(@list.get_first).must_equal 3 - end - - it 'will put the last added item to the front of the list' do - # Act - @list.add_first(1) - @list.add_first(2) - - # Assert - expect(@list.get_first).must_equal 2 - - # Act again - @list.add_first(3) - - # Assert - expect(@list.get_first).must_equal 3 - end - - it 'will return `nil` for `getFirst` if the list is empty' do - # Act-Assert - expect(@list.get_first).must_be_nil - end - end - - describe "length" do - it "will return 0 for an empty list" do - # Act-Assert - expect(@list.length).must_equal 0 - end - - it "will return the length for nonempty lists" do - # Arrange - count = 0 - while count < 5 - @list.add_first(count) - count += 1 - # Act-Assert - expect(@list.length).must_equal count - end - end - end - - describe "addLast & getLast" do - it "will add to the front if the list is empty" do - # Arrange - @list.add_last(1) - # Act-Assert - expect(@list.get_first).must_equal 1 - end - - it "will put new items to the rear of the list" do - # Arrange - @list.add_last(2) - # Act-Assert - expect(@list.length).must_equal 1 - expect(@list.get_last).must_equal 2 - - # Arrange - @list.add_last(3) - # Act-Assert - expect(@list.get_first).must_equal 2 - expect(@list.get_last).must_equal 3 - expect(@list.length).must_equal 2 - - @list.add_last(4) - expect(@list.get_first).must_equal 2 - expect(@list.get_last).must_equal 4 - expect(@list.length).must_equal 3 - end - end - - describe 'get_at_index' do - it 'returns nil if the index is outside the bounds of the list' do - # Act-Assert - expect(@list.get_at_index(3)).must_be_nil - end - - it 'can retrieve an item at an index in the list' do - # Arrange - @list.add_first(1) - @list.add_first(2) - @list.add_first(3) - @list.add_first(4) - - # Act-Assert - expect(@list.get_at_index(0)).must_equal 4 - expect(@list.get_at_index(1)).must_equal 3 - expect(@list.get_at_index(2)).must_equal 2 - expect(@list.get_at_index(3)).must_equal 1 - end - end - - describe 'max and min values' do - it 'returns nil if the list is empty' do - # Act-Assert - expect(@list.find_max()).must_be_nil - expect(@list.find_min()).must_be_nil - end - - it 'can retrieve the max and min values in the list' do - # Arrange - count = 0 - while count < 5 - @list.add_first(count) - expect(@list.find_max).must_equal count - expect(@list.find_min).must_equal 0 - count += 1 - end - @list.add_last(100) - @list.add_first(-12) - - # Act-Assert - expect(@list.find_max).must_equal 100 - expect(@list.find_min).must_equal(-12) - end - end - - describe "delete" do - it "delete from empty linked list is a no-op" do - # Assert - expect(@list.length).must_equal 0 - # Act - @list.delete(4) - # Assert - expect(@list.length).must_equal 0 - end - - it "can delete valid values from list" do - # Arrange - @list.add_last(9) - @list.add_last(10) - @list.add_first(4) - @list.add_first(3) - @list.add_first(2) - - # Act - # delete fist node (requires updating head) - @list.delete(2) - - # Assert - expect(@list.get_first).must_equal 3 - expect(@list.length).must_equal 4 - expect(@list.get_last).must_equal 10 - expect(@list.find_max).must_equal 10 - expect(@list.find_min).must_equal 3 - - # Act (again) - # delete last node - @list.delete(10) - # Assert - expect(@list.get_first).must_equal 3 - expect(@list.length).must_equal 3 - expect(@list.get_last).must_equal 9 - expect(@list.find_max).must_equal 9 - expect(@list.find_min).must_equal 3 - - # delete fist node (requires updating head) - @list.delete(4) - expect(@list.get_first).must_equal 3 - expect(@list.length).must_equal 2 - expect(@list.get_last).must_equal 9 - expect(@list.find_max).must_equal 9 - expect(@list.find_min).must_equal 3 - end - end - - describe "nth_from_the_end" do - it 'returns nil if n is outside the bounds of the list' do - # Act-Assert - expect(@list.find_nth_from_end(3)).must_be_nil - end - - it 'can retrieve an item at index n from the end in the list' do - # Arrange - @list.add_first(1) - @list.add_first(2) - @list.add_first(3) - @list.add_first(4) - - # Act-Assert - expect(@list.find_nth_from_end(0)).must_equal 1 - expect(@list.find_nth_from_end(1)).must_equal 2 - expect(@list.find_nth_from_end(2)).must_equal 3 - expect(@list.find_nth_from_end(3)).must_equal 4 - expect(@list.find_nth_from_end(4)).must_be_nil - end - end - - describe "reverse" do - it 'can retrieve an item at index n from the end in the list' do - # Arrange - @list.add_first(4) - @list.add_first(3) - @list.add_first(2) - @list.add_first(1) - - # Act - @list.reverse - - # Assert - expect(@list.find_nth_from_end(0)).must_equal 1 - expect(@list.find_nth_from_end(1)).must_equal 2 - expect(@list.find_nth_from_end(2)).must_equal 3 - expect(@list.find_nth_from_end(3)).must_equal 4 - end + # Arrange + before do + @list = LinkedList.new + end + + describe "initialize" do + it "can be created" do + + # Assert + expect(@list).must_be_kind_of LinkedList + end + end + + describe "add_first & get_first" do + it "can add values to an empty list" do + # Act + @list.add_first(3) + + # Assert + expect(@list.get_first).must_equal 3 + end + + it "will put the last added item to the front of the list" do + # Act + @list.add_first(1) + @list.add_first(2) + + # Assert + expect(@list.get_first).must_equal 2 + + # Act again + @list.add_first(3) + + # Assert + expect(@list.get_first).must_equal 3 + end + + it "will return `nil` for `getFirst` if the list is empty" do + # Act-Assert + expect(@list.get_first).must_be_nil + end + end + + describe "length" do + it "will return 0 for an empty list" do + # Act-Assert + expect(@list.length).must_equal 0 + end + + it "will return the length for nonempty lists" do + # Arrange + count = 0 + while count < 5 + @list.add_first(count) + count += 1 + # Act-Assert + expect(@list.length).must_equal count + end + end + end + + describe "addLast & getLast" do + it "will add to the front if the list is empty" do + # Arrange + @list.add_last(1) + # Act-Assert + expect(@list.get_first).must_equal 1 + end + + it "will put new items to the rear of the list" do + # Arrange + @list.add_last(2) + # Act-Assert + expect(@list.length).must_equal 1 + expect(@list.get_last).must_equal 2 + + # Arrange + @list.add_last(3) + # Act-Assert + expect(@list.get_first).must_equal 2 + expect(@list.get_last).must_equal 3 + expect(@list.length).must_equal 2 + + @list.add_last(4) + expect(@list.get_first).must_equal 2 + expect(@list.get_last).must_equal 4 + expect(@list.length).must_equal 3 + end + end + + describe "get_at_index" do + it "returns nil if the index is outside the bounds of the list" do + # Act-Assert + expect(@list.get_at_index(3)).must_be_nil + end + + it "can retrieve an item at an index in the list" do + # Arrange + @list.add_first(1) + @list.add_first(2) + @list.add_first(3) + @list.add_first(4) + + # Act-Assert + expect(@list.get_at_index(0)).must_equal 4 + expect(@list.get_at_index(1)).must_equal 3 + expect(@list.get_at_index(2)).must_equal 2 + expect(@list.get_at_index(3)).must_equal 1 + end + end + + describe "max and min values" do + it "returns nil if the list is empty" do + # Act-Assert + expect(@list.find_max()).must_be_nil + expect(@list.find_min()).must_be_nil + end + + it "can retrieve the max and min values in the list" do + # Arrange + count = 0 + while count < 5 + @list.add_first(count) + expect(@list.find_max).must_equal count + expect(@list.find_min).must_equal 0 + count += 1 + end + @list.add_last(100) + @list.add_first(-12) + + # Act-Assert + expect(@list.find_max).must_equal 100 + expect(@list.find_min).must_equal(-12) + end + end + + describe "delete" do + it "delete from empty linked list is a no-op" do + # Assert + expect(@list.length).must_equal 0 + # Act + @list.delete(4) + # Assert + expect(@list.length).must_equal 0 + end + + it "can delete valid values from list" do + + # Arrange + @list.add_last(9) + @list.add_last(10) + @list.add_first(4) + @list.add_first(3) + @list.add_first(2) + + # Act + # delete fist node (requires updating head) + @list.delete(2) + + # Assert + expect(@list.get_first).must_equal 3 + expect(@list.length).must_equal 4 + expect(@list.get_last).must_equal 10 + expect(@list.find_max).must_equal 10 + expect(@list.find_min).must_equal 3 + + # Act (again) + # delete last node + @list.delete(10) + # Assert + expect(@list.get_first).must_equal 3 + expect(@list.length).must_equal 3 + expect(@list.get_last).must_equal 9 + expect(@list.find_max).must_equal 9 + expect(@list.find_min).must_equal 3 + + # delete fist node (requires updating head) + @list.delete(4) + expect(@list.get_first).must_equal 3 + expect(@list.length).must_equal 2 + expect(@list.get_last).must_equal 9 + expect(@list.find_max).must_equal 9 + expect(@list.find_min).must_equal 3 + end + end + + describe "nth_from_the_end" do + it "returns nil if n is outside the bounds of the list" do + # Act-Assert + expect(@list.find_nth_from_end(3)).must_be_nil + end + + it "can retrieve an item at index n from the end in the list" do + # Arrange + @list.add_first(1) + @list.add_first(2) + @list.add_first(3) + @list.add_first(4) + + # Act-Assert + expect(@list.find_nth_from_end(0)).must_equal 1 + expect(@list.find_nth_from_end(1)).must_equal 2 + expect(@list.find_nth_from_end(2)).must_equal 3 + expect(@list.find_nth_from_end(3)).must_equal 4 + expect(@list.find_nth_from_end(4)).must_be_nil + end + end + + describe "reverse" do + it "can retrieve an item at index n from the end in the list" do + # Arrange + @list.add_first(4) + @list.add_first(3) + @list.add_first(2) + @list.add_first(1) + + # Act + @list.reverse + + # Assert + expect(@list.find_nth_from_end(0)).must_equal 1 + expect(@list.find_nth_from_end(1)).must_equal 2 + expect(@list.find_nth_from_end(2)).must_equal 3 + expect(@list.find_nth_from_end(3)).must_equal 4 + end + end + + describe "partition" do + it "can partition a linked list around a given value" do + @list.add_first(3) + @list.add_first(5) + @list.add_first(8) + @list.add_first(5) + @list.add_first(10) + @list.add_first(2) + @list.add_first(1) + @list = @list.partition(5) + + expect(@list.length).must_equal 7 + expect(@list.get_first).must_equal 1 + expect(@list.get_last).must_equal 5 end + end end