-
Notifications
You must be signed in to change notification settings - Fork 1
/
QueueUsingStack.go
110 lines (87 loc) · 1.81 KB
/
QueueUsingStack.go
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package queue
/*
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
*/
type S struct {
items []int
}
func (s *S)Push(val int) {
s.items = append(s.items, val)
}
func (s *S)Pop()int {
if len(s.items) == 0 {
return -1
}
last, butLast := s.items[len(s.items)-1], s.items[0:len(s.items)-1]
s.items = butLast
return last
}
func (s S)Peek() int {
if len(s.items) == 0 {
return -1
}
return s.items[len(s.items)-1]
}
func (s S)IsEmpty()bool {
return len(s.items) == 0
}
func (s *S)Empty() {
s.items = []int{}
}
type MyQueue struct {
stack *S
first int
}
/** Initialize your data structure here. */
func Constructor() *MyQueue {
return &MyQueue{
stack: &S{},
first: -1,
}
}
/** Push element x to the back of queue. */
func (q *MyQueue) Push(x int) {
if q.stack.IsEmpty() {
q.first = x
}
q.stack.Push(x)
}
/** Removes the element from in front of queue and returns that element. */
func (q *MyQueue) Pop() int {
if q.stack.IsEmpty() {
return -1
}
// // pop an item from the stack
item := q.stack.Pop()
// if stack becomes empty, return
// the popped item
if q.stack.IsEmpty() {
return item
}
// recursive call
x := q.Pop()
// push popped item back to the stack
q.Push(item)
// return the result of deQueue() call
return x
}
/** Get the front element. */
func (q *MyQueue) Peek() int {
return q.first
}
/** Returns whether the queue is empty. */
func (q *MyQueue) Empty() bool {
return q.stack.IsEmpty()
}
/**
* Your MyQueue object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Peek();
* param_4 := obj.Empty();
*/