Queue menggunakan Array

Leave a comment

#include <iostream.h>

#define MAX 5

class queue
{
private:
int t[MAX];
int al;      // Add End
int dl;      // Del End

public:
queue()
{
dl=-1;
al=-1;
}

void del()
{
int tmp,j;
if(dl==-1)
{
cout<<“Queue Kosong”;
}
else
{
for(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++;
t[al]=item;
}
else
{
al++;
if(al==MAX)
{
cout<<“Queue Penuh”<<endl;
al–;
//return;
}
else
t[al]=item;
}

}

void display()
{
if(dl!=-1)
{
for(int i=0;i<=al;i++)
cout<<t[i]<<” “;
}
else
cout<<“KOSONG”;
}

};

int main()
{
queue a;
int data[5]={32,23,45,99,24};
int i;

cout<<“Queue sebelum penambahan elemen : “;
a.display();
cout<<endl<<endl;

for(i=0;i<5;i++)
{
a.add(data[i]);
cout<<“Penambahan nomor “<<(i+1)<<” : “;
a.display();
cout<<endl;
}
cout<<endl;
cout<<“Queue setelah penambahan element : “;
a.display();
cout<<endl<<endl;

for(i=0;i<5;i++)
{
a.del();
cout<<“Penghapusan Nomor “<<(i+1)<<” : “;
a.display();
cout<<endl;
}
return 0;
}

Queue Based on Link List

Leave a comment

#include <iostream.h>
#include <stdio.h>
#include <conio.h>

struct node
{
int data;
node *next;
}*front = NULL, *rear = NULL, *p = NULL, *np = NULL;

void push(int x)
{
np = new node;
np->data = x;
np->next = NULL;
if(front == NULL)
{
front = rear = np;
rear->next = NULL;
}
else
{
rear->next = np;
rear = np;
rear->next = NULL;
}
}

int remove()
{
int x;
if (front == NULL)
{
cout<<“empty queue\n”;
}
else
{
p = front;
x = p->data;
front = front->next;
delete(p);
return(x);
}
return(NULL);
}

void main()
{
int n, c = 0, x;
cout<<“Enter the number of values to be pushed into queue\n”;
cin>>n;
while (c < n)
{
cout<<“Enter the value to be entered into queue\n”;
cin>>x;
push(x);
c++;
}
cout<<“\n\nRemoved Values\n\n”;
while(1)
{
if (front != NULL)
cout<<remove()<<endl;
else
break;
}
getch();
}