Here is a topic I began learning not too long ago. I believe it is decently documented throughout the code, but i owe a lot of my appreciation for stacks to borntocode at DreaminCode. He has a great tutorial on different data structures, all of which utilize OOP. You can find the full tutorial here: www.dreamincode.net/forums/showtopic10157.htm
#include<iostream>
using namespace std;
#define MAX 10
class stack //Declaring our stack class
{
private:
int top; //Keeping our stack counter and array private ( not accessable
int array1[MAX]; //from main() )
public:
stack() //Creating our class methods, the first being our constructor
{ //initializing top to -1. This is to signify an empty stack.
top = -1;
};
void push(int a) //Generally we use the terms 'push' and 'pop' when describing the
{ //actions of adding data to a stack and removing it.
if (top < MAX)
{ //The push function checks to make sure the stack is not at MAX
top++; //capacity. It then takes data passed into the function 'int a'
array1[top] = a; //and initializes it to the array. The placement of data within
} //the array is incremented by 'top'.
else
{
cout<<"Stack is full"<<endl;
top--;
}
};
int pop()
{
if (top == -1)
{ //Pop simply checks to see if the stack is empty,
cout<<"Stack is empty"<<endl; //and if not than it will pass the top of the stack
return NULL; //back to main(), set the top of the stack to NULL and
} //decrement the stack.
else
{
int data = array1[top];
array1[top] = NULL;
top--;
return data;
}
}
};
int main()
{
stack dataPass; //Creating an object of the Stack class
dataPass.push(30);
dataPass.push(40); //Using the Stack object we pass values out
dataPass.push(50); //of main()
cout<< dataPass.pop() << " is popped. "<<endl;
cout<< dataPass.pop() << " is popped. "<<endl; //Here we are using our Stack object to 'pop'
cout<< dataPass.pop() << " is popped. "<<endl; //the Stack and decrement it.
cin.get();
}
1 Comments On This Entry
Page 1 of 1
Page 1 of 1
Trackbacks for this entry [ Trackback URL ]
Tags
My Blog Links
Recent Entries
Recent Comments
Search My Blog
1 user(s) viewing
1 Guests
0 member(s)
0 anonymous member(s)
0 member(s)
0 anonymous member(s)
|
|



1 Comments










|