Computer Scientists are Pretty Pessimistic

Friday 17 June 2016

Queue Implementation with link list

Algoritm ::

Q <= x  : // enqueue operation
                l ← getcell
                if l = nil then overflow
                else
                      info ( l ) ← x
                      link ( l ) ← nil
                      link (r ) ← l
                       r ← l
x <= Q : // dequeue operation
                t ← link ( f )
                if t = nil then underflow
                else
                      x ← info ( t )

                      link ( f ) ← link ( t )

CODE ::
#include <iostream>
#include <cstdlib>
using namespace std;
struct node{
    int data;
    struct node *link;
}*t,*r,*f;
void enqueue(int x)
{
    node *l = (node*) malloc(sizeof(node));
    l->data = x;
    l->link = NULL;
    r->link = l;
    r=l;
}
int dequeue()
{
    t=f->link;
    if(t==NULL)
    {
        cout<<"Underflow"<<endl;
        exit(0);
    }
    int x = t->data;
    f->link = t->link;
    return x;
}
int main()
{
    node *head = (node*) malloc(sizeof(node));
    r=head;
    f=head;
    for(int i=0;i<5;i++)
    {
        int x= rand()%100;
        enqueue(x);
    }
    for(int i=0;i<5;i++)
    {
        cout<<dequeue()<<" ";
    }
}

No comments:

Post a Comment