forked from sachuverma/DataStructures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implement Queue using array.cpp
78 lines (68 loc) · 1.71 KB
/
Implement Queue using array.cpp
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
/*
Implement Queue using array
===========================
Implement a Queue using an Array. Queries in the Queue are of the following type:
(i) 1 x (a query of this type means pushing 'x' into the queue)
(ii) 2 (a query of this type means to pop element from queue and print the poped element)
Example 1:
Input:
Q = 5
Queries = 1 2 1 3 2 1 4 2
Output: 2 3
Explanation:
In the first test case for query
1 2 the queue will be {2}
1 3 the queue will be {2 3}
2 poped element will be 2 the
queue will be {3}
1 4 the queue will be {3 4}
2 poped element will be 3
Example 2:
Input:
Q = 4
Queries = 1 3 2 2 1 4
Output: 3 -1
Explanation:
In the second testcase for query
1 3 the queue will be {3}
2 poped element will be 3 the
queue will be empty
2 there is no element in the
queue and hence -1
1 4 the queue will be {4}.
Your Task :
You are required to complete the two methods push() which take one argument an integer 'x' to be pushed into the queue and pop() which returns a integer poped out from othe queue. If the queue is empty, it should return -1 on a pop operation.
Expected Time Complexity: O(1) for both push() and pop().
Expected Auxiliary Space: O(1) for both push() and pop().
Constraints:
1 ≤ Q ≤ 105
1 ≤ x ≤ 105
*/
/*
The structure of the class is
class MyQueue {
private:
int arr[100005];
int front;
int rear;
public :
MyQueue(){front=0;rear=0;}
void push(int);
int pop();
};
*/
//Function to push an element x in a queue.
void MyQueue ::push(int x)
{
arr[rear] = x;
rear++;
}
//Function to pop an element from queue and return that element.
int MyQueue ::pop()
{
if (rear == front)
return -1;
int ans = arr[front];
front++;
return ans;
}