-
Notifications
You must be signed in to change notification settings - Fork 3
/
Stack.rb
73 lines (58 loc) · 1003 Bytes
/
Stack.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# frozen_string_literal: true
load 'LinkedList.rb'
# Start with your code from LinkedList challenge.
class Node
attr_accessor :value, :next_node
def initialize(value, next_node = nil)
@value = value
@next_node = next_node
end
end
class Stack
attr_accessor :head
def push(number)
# your code here
@head = Node.new(number, @head)
end
def pop
return nil if @head.nil?
# your code here
$value = @head.value
@head = @head.next_node
$value
end
end
class Stack2
attr_accessor :list
def initialize
self.list = LinkedList.new
end
def push(number)
@list.add_at(0, number)
end
def pop
@list.remove(0)&.value
end
end
stack = Stack.new
stack2 = Stack.new
stack.push(3)
stack.push(5)
puts stack.pop
stack2.push(3)
stack2.push(5)
puts stack2.pop
# => 5
stack.push(2)
stack.push(7)
puts stack.pop
stack2.push(2)
stack2.push(7)
puts stack2.pop
# => 7
puts stack.pop
puts stack2.pop
# => 2
puts stack.pop
puts stack2.pop
# => 3