FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/java/232_Implement_Queue_using_Stacks.java at master · jakehoare/leetcode · GitHub
jakehoare
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
30
Star
51
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
java
/
232_Implement_Queue_using_Stacks.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
44 lines (37 loc) · 1.26 KB
Breadcrumbs
leetcode
/
java
/
232_Implement_Queue_using_Stacks.java
Copy path
File metadata and controls
44 lines (37 loc) · 1.26 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
https://leetcode.com/problems/implement-queue-using-stacks/
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.
Use stackA to push and stackB to pop. If stackB is empty then transfer all of stackA to stackB (inverts order).
Time - O(1) to push, O(n) (best case is O(1)) to pop and peek.
Space - O(n)
*/
class
MyQueue
{
private
Stack
<
Integer
>
stackA
=
new
Stack
<
Integer
>();
private
Stack
<
Integer
>
stackB
=
new
Stack
<
Integer
>();
// Push element x to the back of queue.
public
void
push
(
int
x
) {
stackA
.
push
(
x
);
}
// Removes the element from in front of queue.
public
void
pop
() {
if
(
stackB
.
isEmpty
())
while
(!
stackA
.
isEmpty
())
stackB
.
push
(
stackA
.
pop
());
int
x
=
stackB
.
pop
();
}
// Get the front element.
public
int
peek
() {
if
(
stackB
.
isEmpty
())
while
(!
stackA
.
isEmpty
())
stackB
.
push
(
stackA
.
pop
());
return
stackB
.
peek
();
}
// Return whether the queue is empty.
public
boolean
empty
() {
return
stackA
.
isEmpty
() &&
stackB
.
isEmpty
();
}
}
Back
|
FazBrowse Home
|
New Git URL