Stack using linked list

    /* Program to implement stack using linked list */

    #include

    #include

    #define new1 (nd*)malloc(sizeof(nd))

    typedef struct stack

    {

        int info;

        struct stack *next;

    }nd;

    void push(nd **ptr)

    {

        nd *c=*ptr;

        if(*ptr==NULL)

        {

            *ptr=new1;

            printf("\nEnter element to push : ");

            scanf("%d",&(*ptr)->info);

            (*ptr)->next=NULL;

        }

        else

        {

            nd *t;

            t=new1;

            printf("\nEnter element to push : ");

            scanf("%d",&t->info);

            while(c->next!=NULL)

                c=c->next;

            t->next=NULL;

            c->next=t;

        }

    }

    void pop(nd **ptr)

    {

        nd *c=*ptr,*t=*ptr,*p;

        if(*ptr==NULL)

            printf("\nStack is empty...");

        else if(t->next==NULL)         // If queue contains single node

        {

            *ptr=NULL;

            free(t);

        }

        else

        {

            while(c->next!=NULL)

            {

                p=c;

                c=c->next;

            }

            p->next=NULL;

            free(c);

        }

    }

    void display(nd *ptr)

    {

        if(ptr==NULL)

            printf("\nStack is empty...\n");

        else

        {

            printf("\nStack  :   ");

            while(ptr!=NULL)

            {

                printf(" %d --> ",ptr->info);

                ptr=ptr->next;

            }

            printf("\b\b\b\b   ");

            printf("\n");

        }

    }

    main()

    {

        nd *h=NULL;

        printf("\nProgram to implement stack using linked list : \n");

        int ch;

        do

        {

            printf("\n[1] Push :");

            printf("\n[2] Pop : ");

            printf("\n[3] Display : ");

            printf("\n[4] Quit : ");

            printf("\nEnter your choice : ");

            scanf("%d",&ch);

            switch(ch)

            {

                case 1:

                    push(&h);

                    display(h);

                    break;

                case 2:

                    pop(&h);

                    display(h);

                    break;

                case 3:

                    display(h);

                    break;

                case 4:    break;

                default: printf("\nEnter correct choice ... ");

                     break;

            }

        }while(ch!=4);

        printf("\n\n");

    }

Top