Skip to content

Instantly share code, notes, and snippets.

@nevalsar
Last active December 29, 2015 20:39
Show Gist options
  • Save nevalsar/7725586 to your computer and use it in GitHub Desktop.
Save nevalsar/7725586 to your computer and use it in GitHub Desktop.
Linked list implementation of Stack and Queue.
#include <iostream>
#include <stdlib.h>
using namespace std;
struct NODE{
int val;
struct NODE *next;
};
typedef struct NODE node;
class stack{
private:
node *top;
public:
stack(){
top = NULL;
}
~stack(){
cout<<"Emptying stack"<<endl;
}
void push(int val){
if(top == NULL){
top = new node;
top->val = val;
return;
}
node *temp = new node;
temp->val = val;
temp->next = top;
top = temp;
cout<<"Pushed "<<top->val<<endl;
}
void pop(){
if(top == NULL){
cout<<"Stack Underflow - not popped"<<endl;
return;
}
cout<<"Popped "<<top->val<<endl;
node *temp = top;
top = top->next;
delete temp;
}
void print(){
node *temp;
cout<<"Stack state : ";
if(top == NULL){
cout<<"<empty>"<<endl;
return;
}
for(temp = top; temp != NULL; temp = temp->next){
cout<<temp->val<<" ";
}
cout<<endl;
}
};
class queue{
private:
node *front;
node *back;
public:
queue(){
front = back = NULL;
}
~queue(){
cout<<"Emptying queue"<<endl;
}
void push(int val){
node *temp = new node;
temp->val = val;
if(back == NULL)
back = temp;
else
front->next = temp;
front = temp;
cout<<"Pushed "<<front->val<<endl;
}
void pop(){
if(back == NULL){
cout<<"Queue empty - not popped"<<endl;
return;
}
cout<<"Popped "<<back->val<<endl;
node *temp = back;
back = back->next;
delete temp;
}
void print(){
node *temp;
cout<<"Queue state : ";
if(back == NULL){
cout<<"<empty>"<<endl;
return;
}
for(temp = back; temp!= NULL; temp = temp->next){
cout<<temp->val<<" ";
}
cout<<endl;
}
};
int main(){
int choice;
stack one;
queue two;
for(choice=0 ;choice != 4;){
cout<<"\n1.Push random\n2.Pop\n3.Print\n4.Stop"<<endl;
cin>>choice;
switch(choice){
case 1:
one.push(rand()%100);
one.print();
break;
case 2:
one.pop();
one.print();
break;
case 3:
one.print();
break;
case 4:
break;
default:
cout<<"Continue"<<endl;
break;
}
}
for(choice=0 ;choice != 4;){
cout<<"\n1.Enqueue random\n2.Dequeue\n3.Print\n4.Stop"<<endl;
cin>>choice;
switch(choice){
case 1:
two.push(rand()%100);
two.print();
break;
case 2:
two.pop();
two.print();
break;
case 3:
two.print();
break;
case 4:
break;
default:
cout<<"Continue"<<endl;
break;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment