Search

Tuesday, November 3, 2015

Stack Using Linked List

#include<stdio.h>

typedef struct node
{
    int data;
    struct node *next;
    struct node *prev;
}NODE;

NODE *start=NULL,*ptr=NULL,*top=NULL;

NODE *Create_node(int val);
void PUSH();
void POP();
void DISPLAY();

void main()
{
    int choice;
    while(1)
    {
        printf("Enter Your Choice\n 1.PUSH \n 2.POP \n 3.DIsplay \nEnter Your Choice:");
        scanf("%d",&choice);
        switch(choice)
        {
            case 1:
                PUSH();
                break;

            case 2:
                POP();
                break;

            case 3:
                DISPLAY();
                break;

            default:
                printf("\nWrong choice\n");
        }
    }
}

NODE *Create_node(int val)
{
    NODE *new_node;
    new_node=(NODE *)malloc(sizeof(NODE));
    new_node->data=val;
    new_node->next=NULL;
    new_node->prev=NULL;
    return new_node;
}

void PUSH()
{
    NODE *new_node;
    int val;
    printf("Enter the Value:");
    scanf("%D",&val);
    new_node=Create_node(val);
    if(start==NULL)
    {
        start=new_node;
        top=new_node;
    }
    else
    {
        new_node->prev=top;
        top->next=new_node;
        top=new_node;
    }
}

void POP()
{
    struct Node *temp, *var=top;
    if(start==NULL)
    {
        printf("\nStack Empty");
    }
    else
    {
        top = top->prev;
        free(top);
        top->next=NULL;
    }

}

void DISPLAY()
{
   NODE *ptr;
   ptr=start;
   printf("DATA\n");
   if(start==NULL)
   {
       printf("Stack is empty");
   }
   else
   {
       while(ptr!=NULL)
       {
           printf("%d\n",ptr->data);
           ptr=ptr->next;
       }
   }
}

No comments:

Post a Comment