Skip to content

Instantly share code, notes, and snippets.

@majedsiefalnasr
Created May 12, 2017 16:33
Show Gist options
  • Save majedsiefalnasr/a27ee7d5381fd4e91b36fe348155144f to your computer and use it in GitHub Desktop.
Save majedsiefalnasr/a27ee7d5381fd4e91b36fe348155144f to your computer and use it in GitHub Desktop.
Stack and Queue classes
#include<iostream>
using namespace std;
class stack{
private:
struct node{
int data;
node *next;
};
node *first, *temp;
void add_first(){
temp->next = first;
first = temp;
}
void delete_first(){
temp = first;
first = first->next;
delete(temp);
}
public:
stack(){
first = NULL;
}
void push(int value){
temp = new node;
temp->data = value;
add_first();
}
int pop(){
int v = first->data;
delete_first();
return v;
}
bool is_empty(){
if (first == NULL)
return true;
else
return false;
}
int get_length(){
int count = 0;
temp = first;
while (temp != NULL){
count++;
temp = temp->next;
}
return count;
}
void clear(){
temp = first;
while (temp != NULL)
delete_first();
}
};
class queue{
private:
struct node{
int data;
node *next;
};
node *first , *temp;
void add_last(){
node *tempx;
tempx = first;
if (tempx != NULL)
{
while (tempx->next != NULL)
tempx = tempx->next;
tempx->next = temp;
}
else
first = temp;
}
void delete_first(){
temp = first;
if (first != NULL)
first = first->next;
delete(temp);
}
public:
queue(){
first = NULL;
}
void enqueue(int value){
temp = new node;
temp->data = value;
temp->next = NULL;
add_last();
}
int dequeue(){
int v = first->data;
delete_first();
return v;
}
bool is_empty(){
if (first == NULL)
return true;
else
return false;
}
int get_length(){
int count = 0;
temp = first;
while (temp != NULL){
count++;
temp = temp->next;
}
return count;
}
void display(){
node *tempx;
tempx = first;
if (tempx != NULL)
{
while (tempx->next != NULL){
cout << tempx->data << endl;
tempx = tempx->next;
}
if (tempx->next == NULL)
cout << tempx->data << endl;
}
else
cout << "there is no values" << endl;
}
void clear(){
temp = first;
while (temp != NULL)
delete_first();
}
};
void main()
{
stack st;
int x;
cout << st.is_empty() << endl;
for (int i = 0; i < 5; i++){
cout << "enter";
cin >> x;
st.push(x);
}
cout << "length = " << st.get_length() << endl;
for (int i = 0; i < 5; i++){
cout << st.pop() << endl;
}
st.clear();
cout << st.is_empty() << endl;
queue qq;
int iteminsert, itemdelete;
cout << "Howmany items you want insert in queue : ";
cin >> iteminsert;
for (int i = 0; i < iteminsert; i++){
cout << "Enter value number " << i + 1 << " : ";
cin >> x;
qq.enqueue(x);
}
cout << "your items is " << endl;
qq.display();
cout << "Howmany items you want to delete : ";
cin >> itemdelete;
for (int i = 0; i < itemdelete; i++){
cout << qq.dequeue() << "\t This item was deleted" << endl;
}
cout << "your items after delete operation is " << endl;
qq.display();
qq.clear();
cin.get(); cin.ignore();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment