مثال على المكدس (stack ) و العمليات عليه
#include <iostream>
using namespace std;
#define MAX 10 // MAXIMUM STACK CONTENT
class stack
{
private:
int arr[MAX]; // Contains all the Data
int top; //Contains location of Topmost Data pushed onto Stack
public:
stack() //Constructor
{
top=-1; //Sets the Top Location to -1 indicating an empty stack
}
void push(int a) // Push ie. Add Value Function
{
top++; // increment to by 1
if(top<MAX)
{
arr[top]=a; //If Stack is Vacant store Value in Array
}
else
{
cout<<"STACK FULL!!"<<endl;
top--;
}
}
int pop() // Delete Item. Returns the deleted item
{
if(top==-1)
{
cout<<"STACK IS EMPTY!!!"<<endl;
return NULL;
}
else
{
int data=arr[top]; //Set Topmost Value in data
arr[top]=NULL; //Set Original Location to NULL
top--; // Decrement top by 1
return data; // Return deleted item
}
}
};
int main()
{
stack a;
int c;
cout<<"please enter 3 no to push them inside the stack ";
for (int i=0;i<=2;i++)
{
cin>>c;
a.push(c);
}
/* For each character from left to right
Get next character
If operand, push it on S
If an operator:
Pop two values (error if there are no two values)
Apply operator
Push result back onto (S)
*/
a.push(a.pop()+a.pop());
a.push(a.pop()+a.pop());
cout<<"there additon is : ";
cout<<"\n"<<a.pop()<<endl;
return 0;
}مثال على الطابور ( queue )
#include <iostream>
using namespace std;
#define MAX 5 // MAXIMUM CONTENTS IN QUEUE
class queue
{
private:
int t[MAX];
int al; // Addition End
int dl; // Deletion End
public:
queue()
{
dl=-1;
al=-1;
}
void del()
{
int tmp;
if(dl==-1)
{
cout<<"Queue is Empty";
}
else
{
for(int j=0;j<=al;j++)
{
if((j+1)<=al)
{
tmp=t[j+1];
t[j]=tmp;
}
else
{
al--;
if(al==-1)
dl=-1;
else
dl=0;
}
}
}
}
void add(int item)
{
if(dl==-1 && al==-1)
{
dl++;
al++;
}
else
{
al++;
if(al==MAX)
{
cout<<"Queue is Full\n";
al--;
return;
}
}
t[al]=item;
}
void display()
{
if(dl!=-1)
{
for(int iter=0 ; iter<=al ; iter++)
cout<<t[iter]<<" ";
}
else
cout<<"EMPTY";
}
};
int main()
{
queue a;
int data[5]={32,23,45,99,24};
cout<<"Queue before adding Elements: ";
a.display();
cout<<endl<<endl;
for(int iter = 0 ; iter < 5 ; iter++)
{
a.add(data[iter]);
cout<<"Addition Number : "<<(iter+1)<<" : ";
a.display();
cout<<endl;
}
cout<<endl;
cout<<"Queue after adding Elements: ";
a.display();
cout<<endl<<endl;
for(iter=0 ; iter < 5 ; iter++)
{
a.del();
cout<<"Deletion Number : "<<(iter+1)<<" : ";
a.display();
cout<<endl;
}
return 0;
}اتمنى انهم ينالوا اعجابكم