Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Include

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

#include <iostream>

using namespace std;


struct node {
int data;
struct node *next;
};
struct node* front = NULL;
struct node* back = NULL;
struct node* temp;
void Insert() {
int val;
cout<<"Insert the element in queue : "<<endl;
cin>>val;
if (back == NULL) {
back = (struct node *)malloc(sizeof(struct node));
back->next = NULL;
back->data = val;
front = back;
} else {
temp=(struct node *)malloc(sizeof(struct node));
back->next = temp;
temp->data = val;
temp->next = NULL;
back = temp;
}
}
void Delete() {
temp = front;
if (front == NULL) {
cout<<"Underflow"<<endl;
return;
}
else
if (temp->next != NULL) {
temp = temp->next;
cout<<"Element deleted from queue is : "<<front->data<<endl;
free(front);
front = temp;
} else {
cout<<"Element deleted from queue is : "<<front->data<<endl;
free(front);
front = NULL;
back = NULL;
}
}
void Display() {
temp = front;
if ((front == NULL) && (back == NULL)) {
cout<<"Queue is empty"<<endl;
return;
}
cout<<"Queue elements are: ";
while (temp != NULL) {
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
int main() {
int ch;
cout<<"1) Insert element to queue"<<endl;
cout<<"2) Delete element from queue"<<endl;
cout<<"3) Display all the elements of queue"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter your choice : "<<endl;
cin>>ch;
switch (ch) {
case 1: Insert();
break;
case 2: Delete();
break;
case 3: Display();
break;
case 4: cout<<"Exit"<<endl;
break;
default: cout<<"Invalid choice"<<endl;
}
} while(ch!=4);
return 0;
}

2.

//Implementation of Queue using Linked List

#include<iostream>

using namespace std;

struct Node{

int data;

Node *next;

};

class Queue{

public:
Node *front,*back;

Queue()

{front=back=NULL;}

void insert(int n);

void deleteitem();

void display();

~Queue();

};

void Queue::insert(int n){

Node *temp=new Node;

if(temp==NULL){

cout<<"Overflow"<<endl;

return;

temp->data=n;

temp->next=NULL;

//for first node

if (front==NULL){

front=back=temp;

else

{ back->next=temp;
back=temp;

cout<<n<<" has been inserted successfully."<<endl;

void Queue::display(){

if (front==NULL){

cout<<"Underflow."<<endl;

return;

Node *temp=front;

//will check until NULL is not found

while(temp){

cout<<temp->data<<" ";

temp=temp->next;

cout<<endl;

void Queue :: deleteitem()

if (front==NULL){

cout<<"underflow"<<endl;

return;

}
cout<<front->data<<" is being deleted "<<endl;

if(front==back)//if only one node is there

front=back=NULL;

else

front=front->next;

Queue ::~Queue()

while(front!=NULL)

Node *temp=front;

front=front->next;

delete temp;

back=NULL;

int main(){

Queue Q;

Q.display();

Q.insert(10);
Q.insert(24);

Q.insert(28);

Q.insert(32);

Q.insert(30);

Q.display();

Q.deleteitem();

Q.deleteitem();

Q.deleteitem();

Q.deleteitem();

Q.deleteitem();

return 0;

You might also like