Computer Scientists are Pretty Pessimistic

Showing posts with label Link List. Show all posts
Showing posts with label Link List. Show all posts

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()<<" ";
    }
}

Stack Implementation with link list

Algorithm ::

S <= x  : // push operation
             
             l ← getcell
             if l = nil then overflow
             else
                    info ( link ) ← x
                    
                    link ( l ) ← t

x <= S : // pop operation
             
             if t = nil then underflow
             else
                    x ← info ( t )

                    t ← link ( t )


CODE ::

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