Stack Operations (push,pop,display and search) using linked list in C Language

 




#include<stdio.h>
#include<conio.h>
struct Node
{
    int data;
    struct Node *next;
}*top = NULL;
void push(int);
void pop();
void search(int);
void display();
void main()
{
    int choice, value;
    clrscr();
    while(1)
    {
        printf("\n\n***** MENU *****\n");
        printf("\n ------------------------------");
        printf("\n 1. Push”");
        printf("\n 2. Pop");
        printf("\n 3. Display");
        printf("\n 4. Search");
        printf("\n 5. Exit");
        printf("\nEnter your choice: ");
        scanf("%d",&choice);
        switch(choice)
        {
            case 1:
                        printf("Enter the value to be insert: ");
                        scanf("%d",&value);
                        push(value);
                        break;
            case 2:
                        pop();
                        break;
            case 3:
                        display();
                        break;
            case 4:
                        printf("Enter the value to be search: ");
                        scanf("%d",&value);
                        search(value);
                        break;
            case 5:
                        exit(0);
            default:
                        printf("\nWrong selection!!! Try again!!!");
        }
    }
}
void push(int value)
{
    struct Node *newNode;
    newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    if(top == NULL)
    {
        newNode->next = NULL;
    }
    else
    {
        newNode->next = top;
    }    
    top = newNode;
    printf("\nNew node is inserted at the top!!!");
}
void pop()
{
    if(top == NULL)
    {
        printf("\nStack Status....: Stack is Empty!!!\n");
        return;
    }
    else
    {
        struct Node *temp = top;
        printf("\nDeleted element: %d", temp->data);
        top = temp->next;
        free(temp);
    }
}
void search(int value)
{
    int n, found=0;
    struct Node *temp;
    temp=top;
    while(temp!=NULL)
    {
        n=temp->data;
        if(n==value)
        {
            found=1;
            break;
        }
        temp=temp->next;
    }
    if(found==1)    
        printf("\n %d found",value);
    else
        printf("\n %d not found",value);
}
void display()
{
    if(top == NULL)
    {
        printf("\n Stack Status ..: Stack is Empty!!!\n");
        return;
    }
    else
    {
        struct Node *temp = top;
        printf("\n Stack Status...:");
        while(temp->next != NULL)
        {
            printf("%d->",temp->data);
            temp = temp -> next;
        }
        printf("%d->NULL",temp->data);
    }
}

Post a Comment

0 Comments