#include <iostream>
#include <stdlib.h>
using namespace std;
class Base{
public:
virtual void push(int) = 0;
virtual int pop() = 0;
};
class Stack : public Base{
int *arr;
int stack_len;
public:
int top;
Stack(int size);
~Stack();
void push(int);
int pop();
void print_stack();
};
Stack::Stack(int size)
{
arr = new int[size];
top = -1;
stack_len = size;
}
Stack::~Stack()
{
delete[] arr;
}
void Stack::push(int item)
{
if((top + 1) < stack_len)
{
cout<<"Pushed "<<item<<endl;
arr[++top] = item;
print_stack();
}
else
{
cout<<"Stack Full!!!";
exit(0);
}
}
int Stack::pop()
{
if(top!= -1)
{
cout<<"Popped "<<arr[top]<<endl;
--top;
print_stack();
}
else
{
cout<<"Stack Empty!!!";
exit(0);
}
}
void Stack::print_stack()
{
int i;
for(i = top ; i > -1 ; i--)
{
cout<<" "<<arr[i];
}
cout<<endl;
}
int main()
{
Stack s1(5);
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
s1.pop();
s1.pop();
}
Master programming effortlessly with Simplest Codings. From core algorithms and LLMs to clean code in Java, C++, and Python—get clear, bite-sized tutorials and practical developer guides for all skill levels.
Friday, July 9, 2010
Simple Stack using Arrays
A Simple stack using arrays.
Subscribe to:
Post Comments (Atom)
-
Overview of the SSL handshake Courtesy: http://www-01.ibm.com/support/knowledgecenter Steps involved in SSL handshake (Courtesy:...
-
To implement the kind of storage which stores strings as the search keys , there is a need to have special data structures which can store ...
-
A simple implementation of a packet sniffer in C on linux platform using the libpcap library. This packet sniffer currently sniffs IP , TCP ...
No comments:
Post a Comment
Please post your valuable suggestions