Skip to content

Instantly share code, notes, and snippets.

@pwneddesal
Created January 27, 2018 07:40
Show Gist options
  • Save pwneddesal/e3e0d1bcd189a5b975ebe742dcb45e57 to your computer and use it in GitHub Desktop.
Save pwneddesal/e3e0d1bcd189a5b975ebe742dcb45e57 to your computer and use it in GitHub Desktop.
//implementing stack using arrays in c++
#include <iostream>
using namespace std;
#define MAX_SIZE 101
class Stack
{
private:
int A[MAX_SIZE];
int top;
public:
// constructor
Stack()
{
top = -1;
}
void Push(int x)
{
if(top == MAX_SIZE -1) {
printf("Error: stack overflow\n");
return;
}
A[++top] = x;
}
void Pop()
{
if(top == -1) {
printf("Error: No element to pop\n");
return;
}
top--;
}
void Print() {
int i;
printf("Stack: ");
for(i = 0;i<=top;i++)
printf("%d ",A[i]);
printf("\n");
}
void Reverse(){
int i;
printf("Stack: ");
for (int i = top; i >=0 ; i--) {
printf("%d ",A[i]);
}
printf("\n");
}
};
int main()
{
Stack S;
printf("inserting numbers:1 to 10 into the stack-> ");
S.Push(1);S.Push(2);S.Push(3);S.Push(4);S.Push(5);S.Push(6);S.Push(7);S.Push(8);S.Push(9);S.Push(10);S.Print();
printf("pop the last item in the stack-> ");
S.Pop();S.Print();
printf("push 12 in the stack -> ");
S.Push(12);S.Print();
printf("reversing the order of the stack -> ");S.Reverse();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment