-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathN_Stacks_In_An_Array.cpp
51 lines (47 loc) · 1.17 KB
/
N_Stacks_In_An_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
#include <bits/stdc++.h>
class NStack
{
private:
int * arr;
int * next;
int * tops;
int freespace;
public:
// Initialize your data structure.
NStack(int N, int S)
{
arr = new int[S];
next = new int[S];
tops = new int[N];
freespace = 0;
for(int i = 0; i < N; i++) {
tops[i] = -1;
}
for(int i = 0; i < S; i++) {
next[i] = i+1;
}
next[S-1] = -1;
}
// Pushes 'X' into the Mth stack. Returns true if it gets pushed into the stack, and false otherwise.
bool push(int x, int m)
{
if(freespace == -1) return false;
int index = freespace;
arr[index] = x;
freespace = next[index];
next[index] = tops[m-1];
tops[m-1] = index;
return true;
}
// Pops top element from Mth Stack. Returns -1 if the stack is empty, otherwise returns the popped element.
int pop(int m)
{
if(tops[m-1] == -1) return -1;
int index= tops[m-1];
int value = arr[index];
tops[m-1] = next[index];
next[index] = freespace;
freespace = index;
return value;
}
};