44Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
55=end
66
7- # # ## List class ###
7+ ### List class ###
88class MyList
99 attr_reader :size # Get list length (current number of elements)
1010 attr_reader :capacity # Get list capacity
1111
12- # # ## Constructor ###
12+ ### Constructor ###
1313 def initialize
1414 @capacity = 10
1515 @size = 0
1616 @extend_ratio = 2
1717 @arr = Array . new ( capacity )
1818 end
1919
20- # # ## Access element ###
20+ ### Access element ###
2121 def get ( index )
2222 # If the index is out of bounds, throw an exception, as below
2323 raise IndexError , "Index out of bounds" if index < 0 || index >= size
2424 @arr [ index ]
2525 end
2626
27- # # ## Access element ###
27+ ### Access element ###
2828 def set ( index , num )
2929 raise IndexError , "Index out of bounds" if index < 0 || index >= size
3030 @arr [ index ] = num
3131 end
3232
33- # # ## Add element at end ###
33+ ### Add element at end ###
3434 def add ( num )
3535 # When the number of elements exceeds capacity, trigger the extension mechanism
3636 extend_capacity if size == capacity
@@ -40,7 +40,7 @@ def add(num)
4040 @size += 1
4141 end
4242
43- # # ## Insert element in middle ###
43+ ### Insert element in middle ###
4444 def insert ( index , num )
4545 raise IndexError , "Index out of bounds" if index < 0 || index >= size
4646
@@ -57,7 +57,7 @@ def insert(index, num)
5757 @size += 1
5858 end
5959
60- # # ## Delete element ###
60+ ### Delete element ###
6161 def remove ( index )
6262 raise IndexError , "Index out of bounds" if index < 0 || index >= size
6363 num = @arr [ index ]
@@ -74,15 +74,15 @@ def remove(index)
7474 num
7575 end
7676
77- # # ## Expand list capacity ###
77+ ### Expand list capacity ###
7878 def extend_capacity
7979 # Create new array with length extend_ratio times original, copy original array to new array
8080 arr = @arr . dup + Array . new ( capacity * ( @extend_ratio - 1 ) )
8181 # Add elements at the end
8282 @capacity = arr . length
8383 end
8484
85- # # ## Convert list to array ###
85+ ### Convert list to array ###
8686 def to_array
8787 sz = size
8888 # Elements enqueue
0 commit comments