Stack implemented as a linked list



#include<stdio.h>
#define max 4
struct node
{
        int data;
        struct node *next;
};
void push(struct node **,int);
void pop(struct node **);
void display(struct node *);
main()

{

        struct node *head;
        head = NULL;
        push(&head,10);
        push(&head,20);
        push(&head,30);
        push(&head,40);
        push(&head,50);
        display(head);
        pop(&head);
        printf("\nafter poping the element the stack is\n");
        display(head);
}
void push(struct node **q,int num)
{
        struct node *temp,*r;
        static int n=1;
        temp = *q;
        if(n<=max)
        {
                temp = (struct node*)malloc(sizeof(struct node));
                temp->data = num;
                temp->next = *q;
 *q = temp;
                n++;
        }
        else
        {
                printf("stack is full\n");
        }
}
void pop(struct node **q)
{
        struct node *temp,*old;
        temp = *q;
        if(temp == NULL)
        {
                printf("stack is empty\n");
        }
        else
        {
        *q = temp->next;
        free(temp);
        }
}
void display(struct node *q)
{
        while(q!=NULL)
        {
                printf("%d  ",q->data);
                q = q->next;
        }
}
-------------------------------------------------------------------------------------------------------------------------------------------
op :
stack is full
40  30  20  10
after poping the element the stack is
30  20  10

Author

Written by Admin

Aliquam molestie ligula vitae nunc lobortis dictum varius tellus porttitor. Suspendisse vehicula diam a ligula malesuada a pellentesque turpis facilisis. Vestibulum a urna elit. Nulla bibendum dolor suscipit tortor euismod eu laoreet odio facilisis.

0 comments: