nord vpnnord vpn
Ad

Stack_Using_linked_list.c

mail@pastecode.io avatar
unknown
c_cpp
20 days ago
2.3 kB
0
Indexable
Never
#include<stdio.h>
#include<stdlib.h>

typedef struct Node
{
    int data;
    struct Node *address;
}Node;

int underflow(Node *top)
{
    if(top == NULL)
    {
        return(1);
    }
    return(0);
}

Node *push(Node *top, int value)
{
    Node *new_node = (Node *)malloc(sizeof(Node));
    new_node->data = value;
    new_node->address = top;
    return(new_node);
}

int pop(Node **top)
{
    if(underflow(*top))
    {
        printf("\nCaution! Stack Underflow Condition!!!\n");
        return -1;
    }
    else
    {
        int popped_element;
        Node *temp = *top;
        *top = (*top)->address;
        popped_element = temp->data;
        free(temp);
        return(popped_element);
    }
}

int peek(Node *top)
{
    if(underflow(top))
    {
        printf("\nCaution! Stack Underflow Condition!!!\n");
        return -1;
    }
    else
    {
        return(top->data);
    }
}

void display(Node *top)
{
    if(underflow(top))
    {
        printf("\nStack is Empty!!!\n");
    }
    else
    {
        Node *temp = top;
        printf("\nItems in the Stack:\n");
        while(temp != NULL)
        {
            printf("%d -> ",temp->data);
            temp = temp->address;
        }
        printf("THE END\n");
    }
}

void main()
{
    Node *top = NULL;
    int user_input, push_ele;
    label:
    printf("\nSelect any of the following options:\n");
    printf("PUSH - 1\nPOP - 2\nPEEK - 3\nDISPLAY - 4\nEXIT CODE - 5\n");
    scanf("%d",&user_input);

    switch (user_input)
    {
    case 1:
        printf("\nEnter the element to be Pushed inside the Stack: ");
        scanf("%d",&push_ele);
        top = push(top, push_ele);
        goto label;
        break;
    case 2:
        printf("\nPoped element from the Stack: %d",pop(&top));
        printf("\n");
        goto label;
        break;
    case 3:
        printf("\nElement on the Top of the Stack: %d",peek(top));
        printf("\n");
        goto label;
        break;
    case 4:
        display(top);
        goto label;
        break;
    case 5:
        printf("\nThank You!!!\n");
        exit(0);
    default:
        printf("\nPlease Select A Valid Option!!!");
        goto label;
        break;
    }
    
}

nord vpnnord vpn
Ad