Skip to content

Instantly share code, notes, and snippets.

@AmosAidoo
Created December 18, 2019 09:55
Show Gist options
  • Save AmosAidoo/dd93c76112a1000f2b5bcc48ac45ff76 to your computer and use it in GitHub Desktop.
Save AmosAidoo/dd93c76112a1000f2b5bcc48ac45ff76 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
void push(int* Sk, int& T, int n); //A helper function
void _empty(int* Sk, int& T, int n); //The answer
int main() {
int n, T;
char c;
bool quit = false;
T = 0;
cout << "Please input the size of the stack : ";
cin >> n;
int Sk[n + 1]; //The Stack
//Push Elements to stack
while (!quit) {
push(Sk, T, n);
cout << "Do you want to continue adding groups? (y or n): ";
cin >> c;
if (c == 'Y' || c == 'y') quit = false;
else if (c == 'N' || c == 'n') quit = true;
else {
cout << "Quitting.... Wrong Input";
break;
}
}
//Empty the stack
_empty(Sk, T, n);
return 0;
}
//A simple function to help push groups into the stack
void push(int* Sk, int& T, int n) {
int m, num;
cout << "m for this group: ";
cin >> m;
if (T >= n) {
cout << "Stack is full\n";
} else {
for (int i = 0; i < m; i++) {
T = T + 1;
cin >> num;
Sk[T] = num;
}
T = T + 1;
Sk[T] = m;
}
}
//This is the answer to the question
void _empty(int* Sk, int& T, int n) {
int groupCount = 0;
do {
//m will be the top-most item on the stack and on subsequent groups
int m = Sk[T];
//Remove all m elements from the stack
T = T - m - 1;
groupCount += 1;
} while (T > 0);
cout << "The number of groups is " << groupCount << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment