Computer Scientists are Pretty Pessimistic

Friday 17 June 2016

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;
}

No comments:

Post a Comment