-
Notifications
You must be signed in to change notification settings - Fork 506
/
Copy pathImplement stack using array.cpp
75 lines (65 loc) · 1.51 KB
/
Implement stack 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
/*
Implement stack using array
===========================
Write a program to implement a Stack using Array. Your task is to use the class as shown in the comments in the code editor and complete the functions push() and pop() to implement a stack.
Example 1:
Input:
push(2)
push(3)
pop()
push(4)
pop()
Output: 3, 4
Explanation:
push(2) the stack will be {2}
push(3) the stack will be {2 3}
pop() poped element will be 3,
the stack will be {2}
push(4) the stack will be {2 4}
pop() poped element will be 4
Example 2:
Input:
pop()
push(4)
push(5)
pop()
Output: -1, 5
Your Task:
You are required to complete two methods push() and pop(). The push() method takes one argument, an integer 'x' to be pushed into the stack and pop() which returns an integer present at the top and popped out from the stack. If the stack is empty then return -1 from the pop() method.
Expected Time Complexity : O(1) for both push() and pop().
Expected Auixilliary Space : O(1) for both push() and pop().
Constraints:
1 <= Q <= 100
1 <= x <= 100
*/
/*
The structure of the class is
class MyStack
{
private:
int arr[1000];
int top;
public:
MyStack(){top=-1;}
int pop();
void push(int);
};
*/
/* The method push to push element into the stack */
void MyStack ::push(int x)
{
if (top == 999)
return;
top++;
arr[top] = x;
}
/*The method pop which return the element
poped out of the stack*/
int MyStack ::pop()
{
if (top == -1)
return -1;
int ans = arr[top];
top--;
return ans;
}