Stack (Using Link List)

Stack: (Using Link list )



#include<stdio.h>        ///**********hope, this is Most Efficient Code *******
typedef struct node        ///*********also simple to understand *** LIFO *** *******
{
    int dat;
    struct node *ptr;
}link;

link *head=NULL;

void push();
void pop();
void print();

int main()
{
    int n;
    while(1)
    {
        printf("1. To Push\n2. To Pop\n3. To Print\n4. To Exit \t\t -> Give choice :");
        scanf("%d",&n);
        puts("");
        if(n==1)
            push();
        else if(n==2)
            pop();
        else if(n==3)
            print();
        else if(n==4)
            break;
        else
            printf("Invalid Choice\n");
    }
    delete head;
return 0;
}

void push()
{
    int y;
    link *tmptr = new link ;
    scanf("%d",&y);
   
    if(tmptr!=NULL)
    {
        tmptr->dat=y;
        tmptr->ptr=head;    // 1st case head=NULL, but then head=previous data that i store

        head=tmptr;        // Swaping, now current value and previous value are in head
    }
    else
        printf("Memory Full\n");
}

void pop()
{
    if(head!=NULL)
        head=head->ptr;
    else
        printf("Stack Is Empty\n");
}

void print()
{
    link *tem;
    tem= new link;
    tem= head;

    printf("\n\t-");
    while(tem!=NULL)
        {
            printf("-> %d",tem->dat);
            tem=tem->ptr;
        }
    printf("\n\n");
}

মন্তব্যসমূহ