Skip to content

Commit 3962b53

Browse files
committed
Finished stacks questions and tests passing, updated methods
1 parent 12e7397 commit 3962b53

File tree

3 files changed

+28
-17
lines changed

3 files changed

+28
-17
lines changed

lib/queue.rb

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,36 @@ def initialize
77
end
88

99
def enqueue(element)
10+
#Circular buffer method
1011
#Check if queue is empty
1112
if @front == -1 && @back == -1
1213
@front = 0
1314
@back = 1
1415
end
15-
#Check if queue is full
16-
if @front == @back
17-
#Decide what to do if circular buffer is full
18-
end
1916

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
2221

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
2424
@back = (@back + 1) % @store.length
2525
end
2626

2727
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
2940
end
3041

3142
def front

lib/stack.rb

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,23 @@
1+
require_relative './linked_list.rb'
2+
13
class Stack
24
def initialize
3-
# @store = ...
4-
raise NotImplementedError, "Not yet implemented"
5+
@store = LinkedList.new
56
end
67

78
def push(element)
8-
raise NotImplementedError, "Not yet implemented"
9+
@store.add_last(element)
10+
return @store
911
end
1012

1113
def pop
12-
raise NotImplementedError, "Not yet implemented"
14+
return @store.remove_last if @store.get_first != nil
1315
end
1416

1517
def empty?
16-
raise NotImplementedError, "Not yet implemented"
18+
if @store.get_first == nil
19+
return true
20+
end
1721
end
1822

1923
def to_s

test/stack_test.rb

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
end
1818

1919
it "pushes multiple somethings onto a Stack" do
20-
skip
2120
s = Stack.new
2221
s.push(10)
2322
s.push(20)
@@ -26,13 +25,11 @@
2625
end
2726

2827
it "starts the stack empty" do
29-
skip
3028
s = Stack.new
3129
s.empty?.must_equal true
3230
end
3331

3432
it "removes something from the stack" do
35-
skip
3633
s = Stack.new
3734
s.push(5)
3835
removed = s.pop
@@ -41,7 +38,6 @@
4138
end
4239

4340
it "removes the right something (LIFO)" do
44-
skip
4541
s = Stack.new
4642
s.push(5)
4743
s.push(3)

0 commit comments

Comments
 (0)