File tree Expand file tree Collapse file tree 3 files changed +28
-17
lines changed Expand file tree Collapse file tree 3 files changed +28
-17
lines changed Original file line number Diff line number Diff line change @@ -7,25 +7,36 @@ def initialize
7
7
end
8
8
9
9
def enqueue ( element )
10
+ #Circular buffer method
10
11
#Check if queue is empty
11
12
if @front == -1 && @back == -1
12
13
@front = 0
13
14
@back = 1
14
15
end
15
- #Check if queue is full
16
- if @front == @back
17
- #Decide what to do if circular buffer is full
18
- end
19
16
20
- @store ( @back ) = element
21
- @back += 1
17
+ #Check if queue is full
18
+ if ( ( @back + 1 ) % @store . length ) == @front
19
+ raise ArgumentError . new ( "Queue is full!" )
20
+ end
22
21
23
- #Make it wrap around when it reaches the end
22
+ @store [ @back ] = element
23
+ #Make it wrap around when it reaches the end & use modulo to not go over the end
24
24
@back = ( @back + 1 ) % @store . length
25
25
end
26
26
27
27
def dequeue
28
- raise NotImplementedError , "Not yet implemented"
28
+ if @front == @back
29
+ raise ArgumentError . new ( "Queue is empty!" )
30
+ end
31
+
32
+ #Store the current first element in a temp
33
+ temp = @store [ @front ]
34
+ #Make the front element nil
35
+ @store [ @front ] = nil
36
+
37
+ @front = ( @front + 1 ) % @store . length
38
+
39
+ return temp
29
40
end
30
41
31
42
def front
Original file line number Diff line number Diff line change
1
+ require_relative './linked_list.rb'
2
+
1
3
class Stack
2
4
def initialize
3
- # @store = ...
4
- raise NotImplementedError , "Not yet implemented"
5
+ @store = LinkedList . new
5
6
end
6
7
7
8
def push ( element )
8
- raise NotImplementedError , "Not yet implemented"
9
+ @store . add_last ( element )
10
+ return @store
9
11
end
10
12
11
13
def pop
12
- raise NotImplementedError , "Not yet implemented"
14
+ return @store . remove_last if @store . get_first != nil
13
15
end
14
16
15
17
def empty?
16
- raise NotImplementedError , "Not yet implemented"
18
+ if @store . get_first == nil
19
+ return true
20
+ end
17
21
end
18
22
19
23
def to_s
Original file line number Diff line number Diff line change 17
17
end
18
18
19
19
it "pushes multiple somethings onto a Stack" do
20
- skip
21
20
s = Stack . new
22
21
s . push ( 10 )
23
22
s . push ( 20 )
26
25
end
27
26
28
27
it "starts the stack empty" do
29
- skip
30
28
s = Stack . new
31
29
s . empty? . must_equal true
32
30
end
33
31
34
32
it "removes something from the stack" do
35
- skip
36
33
s = Stack . new
37
34
s . push ( 5 )
38
35
removed = s . pop
41
38
end
42
39
43
40
it "removes the right something (LIFO)" do
44
- skip
45
41
s = Stack . new
46
42
s . push ( 5 )
47
43
s . push ( 3 )
You can’t perform that action at this time.
0 commit comments